當(dāng)前位置:首頁 > IT技術(shù) > 移動(dòng)平臺 > 正文

文字隨著鼠標(biāo)移動(dòng)而移動(dòng)(文字拖拽移動(dòng))
2021-09-16 11:54:04

代碼說明:

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拖動(dòng)部分:

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
    };

}

效果圖片:

原始位置:

?

?

跟隨鼠標(biāo)移動(dòng)后的位置:

?

代碼處理完成,復(fù)制代碼即可用。希望可以幫到大家?。。。?/p>

本文摘自 :https://www.cnblogs.com/

開通會(huì)員,享受整站包年服務(wù)立即開通 >