div设置contenteditable="true" 光标消失:原因

时间:2022-04-26 06:27:46

原因1:document.onselectstart= function(){return false;};

原因2:父层设置了user-select:none 导致 子层设置了 contenteditable 会出现异常,但是在ie和chrome并没有体现出来

如果把编辑框换成input标签不会由于禁止文本选中而出现光标消失的情况了,可以自己尝试

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
*{margin:0;padding:0;}
body{position:relative;}
.call-bulk{
position: absolute;
top: 50px;
left: 0;
width:500px;
height: 100px;
background-image: url(http://og0bztn1p.bkt.clouddn.com//niannianyun/uploadFiles/nn_imgs/author_img/20170823101025wAC.png);
background-position: center bottom;
background-repeat: no-repeat;
background-size: 100% auto;
}
.call{
position: absolute;
left: 0;
bottom: 14px;
width: 100%;
height: 25px;
font-size: 18px;
line-height: 25px;
}
div[contenteditable="true"]:empty:before{
content: attr(placeholder);
color: #BAB3AF;
/*padding: 10px 0;*/
-webkit-tap-highlight-color:transparent;
-webkit-user-modify:read-write;
outline:none;
border:none;
}
</style>
</head>
<body>
<div class="call-bulk" id="call-bulk">
<div class="call" contenteditable="true" placeholder="称呼"></div>
<!-- <input type="text" class="call" placeholder="称呼"> -->
</div>
<button id="btn">换背景</button>
<script>
var imgUrl = [
'http://og0bztn1p.bkt.clouddn.com//niannianyun/uploadFiles/nn_imgs/author_img/20170825151639dY8.png',
'http://og0bztn1p.bkt.clouddn.com//niannianyun/uploadFiles/nn_imgs/author_img/20170823101025wAC.png',
'http://og0bztn1p.bkt.clouddn.com//niannianyun/uploadFiles/nn_imgs/author_img/20170825160657xsv.png',
'http://og0bztn1p.bkt.clouddn.com//niannianyun/uploadFiles/nn_imgs/author_img/20170822111147c5U.png',
'http://og0bztn1p.bkt.clouddn.com//niannianyun/uploadFiles/nn_imgs/author_img/20170825151639vlO.png'
];
var callBulk = document.getElementById('call-bulk');
var Btn = document.getElementById('btn');
var len = imgUrl.length;
Btn.onclick = function(){
var i = Math.floor(len*Math.random());//(0-1)*5 = 0-5的随机数不包括5,向下取整
// x=Math.random() 0<= x < 1
console.log(1);
console.log(i);
var bgurli = 'url('+ imgUrl[i] + ')';
callBulk.style.cssText = 'background-image:'+ bgurli;
document.onselectstart= function(){return false;};
}
</script>
</body>
</html>