主要利用触发鼠标事件实现对css的更改,进而实现盒子位置的变动

首先新建一个div

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>盒子移动</title>
    <link rel="stylesheet" href="css/css-1.css">
    <script type="text/javascript" src="js/js-1.js"></script>
</head>
<body>
    <div id="box" ></div>
</body>
</html>

为这个盒子写入样式

#box{
    position:absolute;
    display:block;
    width:200px;
    height:200px;
    background:red;
    cursor:move;
}

javascript盒子的拖拽(鼠标事件练习)

以下是js代码

window.onload = function() {
    var box = document.getElementById('box');
    box.onmousedown = function (e) {
        var X = e.clientX - box.offsetLeft;
        var Y = e.clientY - box.offsetTop;

        document.onmousemove = function(e)
        {
            var left = e.clientX - X;  
            var top = e.clientY - Y;
            //确保盒子左,上不会被拖出屏幕,右,下不会出现滚动条
            if(left<0){
                left=0;
            }else if(left > window.innerWidth - box.offsetWidth){
                left = window.innerWidth - box.offsetWidth;
            }
            if(top<0){
                top=0;
            }else if(top > window.innerHeight- box.offsetHeight){
                top = window.innerHeight - box.offsetHeight;
            }
            //更改css样式
            box.style.left = left + 'px';
            box.style.top = top + 'px';
        };
        document.onmouseup = function (e) {
            this.onmousemove = null;
        };
    };
};

以上没有考虑浏览器兼容问题

相关文章:

  • 2021-11-28
  • 2022-12-23
  • 2022-02-08
  • 2022-02-08
  • 2021-11-28
  • 2021-11-28
  • 2021-11-28
  • 2022-12-23
猜你喜欢
  • 2022-02-08
  • 2021-07-15
  • 2021-11-28
  • 2021-09-09
  • 2022-02-08
  • 2022-02-08
  • 2022-02-08
相关资源
相似解决方案