文字随着鼠标移动而移动(文字拖拽移动)

代码说明:

html部分:

  

<html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <title>拖拽文字选中</title>
    <script type="text/javascript" src="/image/move_img.js"></script>
    <style>
        #div1 {
            width: 100px;
            height: 100px;
            /*background: red;*/
            position: absolute;
        }
    </style>

</head>

<body>
   <div id="div1">jghjhukj1111<br/>huhujhjgj111</div>
</body>
</html>

js拖动部分:

window.onload = function () {
    var oDiv = document.getElementById('div1');

    var disX = 0;
    var disY = 0;

    oDiv.onmousedown = function (ev) {
        var oEvent = ev || event;

        disX = oEvent.clientX - oDiv.offsetLeft;
        disY = oEvent.clientY - oDiv.offsetTop;

        if (oDiv.setCapture) {
            //IE
            oDiv.onmousemove = mouseMove;
            oDiv.onmouseup = mouseUp;

            oDiv.setCapture();//IE
        } else {
            //chrome,ff
            document.onmousemove = mouseMove;
            document.onmouseup = mouseUp;
        }

        function mouseMove(ev) {
            var oEvent = ev || event;
            var left = oEvent.clientX - disX;
            var top = oEvent.clientY - disY;

            oDiv.style.left = left + 'px';
            oDiv.style.top = top + 'px';
        }

        function mouseUp() {
            this.onmousemove = null;
            this.onmouseup = null;

            if (oDiv.releaseCapture) {
                oDiv.releaseCapture();//IE
            }
        }

        return false;//chrome,ff,IE9
    };

}

效果图片:

原始位置:

 

 

跟随鼠标移动后的位置:

 

代码处理完成,复制代码即可用。希望可以帮到大家!!!!

posted @ 2021-09-16 11:01  划边逅  阅读(432)  评论(0编辑  收藏  举报