其他分享
首页 > 其他分享> > 拖拽事件

拖拽事件

作者:互联网

拖拽

拖拽box1元素

//获取box1
var box1 = document. getElementById("box1");
//为box1绑定一个鼠标按下事件
//当鼠标在被拖拽元素上按下时,开始拖拽onmousedown
box1.onmousedown = function(){
//为document绑定一个onmousemove事件
    document.onmousemove = function(event){
        event = event||window.event;
//当鼠标移动时被拖拽元素跟随鼠标移动onmousemove
//获取鼠标的坐标
        var left = event.clientX;
        var top = event.clientY;
        
        //为元素绑定一个鼠标松开事件
document.onmouseup = function(){
//当鼠标松开时,被拖拽元素固定在当前位置onmouseup
//取消document的onmous emove事件
doc ument.onmousemove = null;
doc ument.onmouseup = null;
    //当鼠标松开时,取消对事件的捕获
box1.releaseCapture();
};
return false;
};
};

每次拖拽时,box左上角都会与鼠标对齐,所以需要进行优化

计算鼠标与box接触时的位置,与box左上角的位置,

//为box1绑定一个鼠标按下事件
//当鼠标在被拖拽元素上按下时,开始拖拽onmousedown
box1. onm ousedown = function(event){
event = event||window.event ;
//div的偏移量鼠标.clentX -元素.offsetLeft
//div的偏移量鼠标.clentY -元素.offsetTop
var ol = event.clientX - box1.offsetLeft;
var ot = event.clientY - box1.offsetTop;
//为document绑定一个onmousemove事件
document.onmousemove = function(event){
event = event|| window.event;
//当鼠标移动时被拖拽元素跟随鼠标移动onmousemove
//获取鼠标的坐标
var left = event.clientX - ol;
var top = event.clientY - ot;
//修改box1的位置
box1.style.left = left+"px";
box1.style.top = top+"px";
};

当我们拖拽一个网页中的内容时,浏览器会默认去搜索引擎中搜索内容,
此时会导致拖拽功能的异常,这个是浏览器提供的默认行为,
如果不希望发生这个行为,则可以通过return false来取消默认行为

但是,对IE8无效

标签:鼠标,拖拽,当鼠标,onmousemove,事件,box1,event
来源: https://www.cnblogs.com/wzx-blog/p/15874815.html