CSS中-webkit-user-select:none; 的用途(控制页面文字无法选中)
出现了选中文字后无法拖拽盒子的bug
本人用js写当鼠标拖拽让一个盒子位置随鼠标位置改动时,遇到了一个bug
效果图如下:
bug如下:
bug描述:当鼠标选中文字后,拖动盒子,但是松开时盒子还是跟着动,这样达不到松开盒子不动的目的
废话不多说,直接上代码:
JS代码
<script type="text/javascript">
var box = document.getElementById('box');
var tou = document.getElementById('tou');
var boxX,boxY;
var mouseX,mouseY;
tou.addEventListener('mousedown',function(e){
mouseX = e.pageX - box.offsetLeft;//鼠标距离盒子的位置
mouseY = e.pageY - box.offsetTop;
document.onmousemove = move;
document.addEventListener('mouseup',function(e){
document.onmousemove = null;
})
return false;
})
function move(e){
boxX = e.pageX - mouseX
boxY = e.pageY - mouseY
box.style.left = boxX + 'px';
box.style.top = boxY + 'px';
console.log(box.offsetLeft)
}
aa.onclick = function(){
box.style.display = 'none';
}
</script>
HTML 代码 HTML codes
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<style type="text/css">
#box{
position: relative;
left: 0px;
top: 0px;
background: whitesmoke;
width: 18rem;
height: 15rem;
border: 0.15rem solid #ccc;
box-shadow: 1px 1px 2px #000,-1px -1px 2px #ccc inset;
}
#box a{
color: white;
font-size: 0.775rem;
text-decoration: none;
margin-right: 5px;
}
#box p{
line-height: 0;
font-size: 0.775rem;
}
#box div{
background: cadetblue;
margin: 5px;
color: white;
display: flex;
align-items: center;
justify-content: space-between;
height: 20px;
cursor: move;
-webkit-user-select:none; --------->用在这里哦
-moz-user-select:none; ----------->用在这里哦
}
#box a:hover{
color: #FF0000;
cursor: pointer;
}
</style>
</head>
<body>
<div id="box">
<div id = 'tou'>
<p id="p">注册信息(可以拖拽)</p>
<a href="#" id="aa">[关闭]</a>
</div>
</div>
<script>这里是上面的js代码哦</script>
</body>
</html>
###发现了bug,选中文字后无法进行松开释放拖拽,于是采用了-webkit-user-select:none;