原生js实现可拖拽功能

2020-05-18  本文已影响0人  Iamsoulmate

原生js实现一个可全局拖拽的按钮功能,直接上代码
*js部分

var downX , downY;
var div = document.getElementsByTagName("div")[0];  
div.addEventListener("mousedown",function(e){
    downX = e.pageX-parseInt(div.style.left);
    downY = e.pageY-parseInt(div.style.top);
    window.addEventListener("mousemove",move);  
    window.addEventListener("mouseup",function(){
        window.removeEventListener("mousemove",move);
    })  
})
function move(e){
    div.style.left = (e.pageX - downX) + "px";
    div.style.top = (e.pageY - downX) + "px";
}

*html部分

<div style="position:absolute;
            left:100px;
            top:100px">
            分享
</div>

*css部分

div{
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background-color: #f40;
    line-height: 100px;
    text-align: center;
    color: white;
    font-size: 20px;
}
上一篇下一篇

猜你喜欢

热点阅读