<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#box1{
width:100px;
height:100px;
background: orangered;
position: absolute;
}
#box2{
width:100px;
height:100px;
background: hotpink;
position: absolute;
left:110px;
}
img{
width:100px;
height:100px;
position: absolute;
left:220px;
}
</style>
</head>
<body>
<div id="box1"></div>
<div id="box2"></div>
<img src="img/1.jpg" id="img" />
<script>
//调用函数drag,实现拖拽,参数为Id名
drag("box1");
drag("box2");
drag("img");
function drag(id){
var obj = document.getElementById(id);//通过Id获取对象
obj.onmousedown=function(evt){//当前对象的鼠标按下事件
var e = evt || window.event;//事件监听的兼容(标准浏览器和IE)
var disX=e.offsetX;//获取当前事件的相对X坐标
var disY=e.offsetY;//获取当前事件的相对X坐标
document.onmousemove=function(evt){//文档的鼠标移动事件,因为对象是在文档内移动
evt = evt || window.event;//事件监听的兼容
obj.style.left=evt.pageX-disX+'px';//获取对象的左边定位=当前事件绝对位置-相对位置
obj.style.top=evt.pageY-disY+'px';/获取对象的左边定位=当前事件绝对位置-相对位置
}
document.onmouseup=function(){//文档的鼠标抬起事件
document.onmousemove=null;//让鼠标移动事件为空,当鼠标抬起时,停止移动
}
//阻止拖拽的默认行为,比如图片会先拖出影子,最后在改变位置,会出现禁止拖拽的标志
document.ondragstart=function(){
return false;
}
}
}
</script>
</body>
JS阻止拖拽的默认行为
最新推荐文章于 2023-11-13 10:45:37 发布