<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
<style>
*{
margin:0;
padding:0;
}
.box{
width:100px;
height:100px;
background-color: lime;
position:absolute;
}
</style>
<script>
window.onload = function(){
var box = document.querySelector('.box');
var divX,divY;
//当鼠标按下时执行
box.onmousedown = function(event){
var e = event || window.event;
// 鼠标在div的位置
divX = e.clientX - box.offsetLeft;
divY = e.clientY - box.offsetTop;
//当鼠标移动时执行
document.onmousemove = function(event){
var e = event || window.event;
box.style.left = e.clientX - divX + 'px';
box.style.top = e.clientY - divY + 'px';
}
// 当鼠标松开时执行
box.onmouseup = function(){
// 消除onmousemove和onmouseup事件
document.onmousemove = null;
box.onmouseup = null;
}
}
}
</script>
</head>
<body>
<div class="box"></div>
</body>
</html>
javascript之event属性案例拖拽效果
猜你喜欢
转载自blog.csdn.net/persistsss/article/details/105520692
今日推荐
周排行