onmousedown活用之鼠标拖动

时间:2022-03-27 02:21:29

这个布局蛮简单的就是一个div块,通过定位,固定位置

 <html>

 <head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#div {
width: 200px;
height: 200px;
background: pink;
position: absolute;
top: 0;
left: 0;
cursor: pointer;
}
</style>
</head> <body>
<div id="div"> </div>
<div id="div2"></div>
</body> </html>

在js代码中需要用到onmousedown和onmouseup这一对方法来实现

而o=event||ev;event表示一般浏览器,而ev则表示ie浏览器,所以o就可以在不同的浏览器中同样实现相同效果

 <script type="text/javascript">
var Div = document.getElementById("div");
Div.onmousedown = function(ev) {
var o = event || ev;
//获取到鼠标点击的位置距离div左侧和顶部边框的距离
oX = o.clientX - parseInt(getStyle(Div, "left"));
oY = o.clientY - parseInt(getStyle(Div, "top"));
//当鼠标移动,把鼠标的偏移量给div
document.onmousemove = function(ev) {
var o = event || ev;
//计算出鼠标在XY方向上移动的偏移量,把这个偏移量加给DIV的左边距和上边距,div就会跟着移动
Div.style.left = o.clientX - oX + "px";
Div.style.top = o.clientY - oY + "px";
} //当鼠标按键抬起,清除移动事件
document.onmouseup = function() {
document.onmousedown = null;
document.onmousemove = null;
}
} //获取属性的数值
function getStyle(obj, attr) {
if (obj.currentStyle) {
//currentStyle获取样式的值,对应的是ie浏览器
return obj.currentStyle[attr];
} else {
//同理,对应的是其他浏览器
return getComputedStyle(obj, false)[attr];
}
}
</script>