addEventListener()方法用于指向元素添加事件,注意在IE8及更早版本,opera7.0及更早版本都不支持addEventListener(),但是可以使用attchEvent()方法来进行添加事件
提示:使用removeEventListener()来溢出addEventListener()方法添加事件
代码实现部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div style="width:100px; height:100px;position:absolute;left:0;top:0;background-color: red;"></div>
<script type="text/javascript">
var div = document.getElementsByTagName('div')[0];
var disx,
disy;
div.addEventListener('mousedown',function(e){
disx = e.pageX - parseInt(div.style.left);//记录鼠标当前的位置
disy = e.pageY - parseInt(div.style.top);
document.addEventListener('mousemove',mouseM)
function mouseM(e){
var event = e||window.event;//兼容了ie浏览器
div.style.left = e.pageX - disx + "px";
div.style.top = e.pageY - disy + "px";
}
div.addEventListener('mouseup',function(){
var event = e||event;
document.removeEventListener('mousemove',mouseM);
})
})
</script>
</body>
</html>
如有错误欢迎提醒,共同学习