欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

js實(shí)現(xiàn)簡單的拖拽效果

 更新時間:2021年09月23日 09:30:12   作者:奔跑的肉夾饃_  
這篇文章主要為大家詳細(xì)介紹了js實(shí)現(xiàn)簡單的拖拽效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實(shí)例為大家分享了js實(shí)現(xiàn)簡單的拖拽效果的具體代碼,供大家參考,具體內(nèi)容如下

1.拖拽的基本效果

思路:

鼠標(biāo)在盒子上按下時,準(zhǔn)備移動 (事件加給物體)

鼠標(biāo)移動時,盒子跟隨鼠標(biāo)移動 (事件添加給頁面)

鼠標(biāo)抬起時,盒子停止移動 (事件加給頁面)

var o = document.querySelector('div');
 
        //鼠標(biāo)按下
        o.onmousedown = function (e) {
            //鼠標(biāo)相對于盒子的位置
            var offsetX = e.clientX - o.offsetLeft;
            var offsetY = e.clientY - o.offsetTop;
            //鼠標(biāo)移動
            document.onmousemove = function (e) {
                o.style.left = e.clientX - offsetX + "px";
                o.style.top = e.clientY - offsetY + "px";
            }
            //鼠標(biāo)抬起
            document.onmouseup = function () {
                document.onmousemove = null;
                document.onmouseup = null;
            }
        }

2.拖拽的問題

若盒子中出現(xiàn)了文字,或盒子自身為圖片,由于瀏覽器的默認(rèn)行為(文字和圖片本身就可以拖拽),我們可以設(shè)置return false來阻止它的默認(rèn)行為,但這種攔截默認(rèn)行為在IE低版本中,不適用,可以使用全局捕獲來解決IE的問題。

全局捕獲

全局捕獲僅適用于IE低版本瀏覽器。

<button>btn1</button>
    <button>btn2</button>
    <script>
        var bts = document.querySelectorAll('button')
 
        bts[0].onclick = function () {
            console.log(1);
        }
        bts[1].onclick = function () {
            console.log(2);
        }
 
        // bts[0].setCapture()  //添加全局捕獲
        // bts[0].releaseCapture() ;//釋放全局捕獲
</script>

一旦為指定節(jié)點(diǎn)添加全局捕獲,則頁面中其它元素就不會觸發(fā)同類型事件。

3.完整版的拖拽

var o = document.querySelector('div');
 
        //鼠標(biāo)按下
        o.onmousedown = function (e) {
            if (o.setCapture) {   //IE低版本
                o.setCapture()
            }
            e = e || window.event
            //鼠標(biāo)相對于盒子的位置
            var offsetX = e.clientX - o.offsetLeft;
            var offsetY = e.clientY - o.offsetTop;
            //鼠標(biāo)移動
            document.onmousemove = function (e) {
                e = e || window.event
                o.style.left = e.clientX - offsetX + "px";
                o.style.top = e.clientY - offsetY + "px";
            }
            //鼠標(biāo)抬起
            document.onmouseup = function () {
                document.onmousemove = null;
                document.onmouseup = null;
                if (o.releaseCapture) {
                    o.releaseCapture();//釋放全局捕獲   
                }
            }
            return false;//標(biāo)準(zhǔn)瀏覽器的默認(rèn)行為
        }

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論