亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術(shù)文章
文章詳情頁

原生JS實(shí)現(xiàn)拖拽功能

瀏覽:85日期:2024-04-09 16:08:23

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

拖拽的原理:三個(gè)事件 onmousedownonmousemove、onmousemove

1、鼠標(biāo)按下,觸發(fā)onmousedown,獲取鼠標(biāo)坐標(biāo)x,y,獲取元素坐標(biāo)x,y

通過event.clientX、event.clientY獲取鼠標(biāo)位置的坐標(biāo)

let x = e.clientX - box.offsetLeft; //鼠標(biāo)點(diǎn)擊坐標(biāo)距離盒子左邊緣的距離let y = e.clientY - box.offsetTop; //鼠標(biāo)點(diǎn)擊坐標(biāo)距離盒子上邊緣的距離

2、設(shè)置元素left、top值,(元素要設(shè)置position:absolute)

box.style.left = ev.clientX - x + ’px’;box.style.top = ev.clientY - y + ’px’;

3、放開鼠標(biāo)取消dom事件

下面是詳細(xì)代碼:我只開了橫向移動(dòng)

<!DOCTYPE html><html lang='en'> <head> <meta charset='UTF-8'> <meta name='viewport' content='width=device-width, initial-scale=1.0'> <meta http-equiv='X-UA-Compatible' content='ie=edge'> <title>Document</title> <style> #box { width: 100px; height: 100px; background: red; position: absolute } </style></head> <body style='position: relative;overflow: hidden;'> <div id='box'> </div> <script> window.onload = function () { let box = document.getElementById(’box’) box.onmousedown = function (ev) { let e = ev || event; let x = e.clientX - box.offsetLeft; //鼠標(biāo)點(diǎn)擊坐標(biāo)距離盒子左邊緣的距離 let y = e.clientY - box.offsetTop; //鼠標(biāo)點(diǎn)擊坐標(biāo)距離盒子上邊緣的距離 document.onmousemove = function (ev) { let e = ev || event; box.style.left = ev.clientX - x + ’px’; box.style.top = ev.clientY - y + ’px’; let bodyScreenX = ev.screenX let bodyClientWidth = document.body.clientWidth document.onmouseup = function (ev) { if (ev.clientX - x < 0) { box.style.left = 0 } else if (bodyScreenX > bodyClientWidth) { box.style.right = 0 box.style.left = bodyClientWidth - 100 + ’px’ } document.onmousemove = null; document.onmouseup = null; } } } } </script></body> </html>

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: JavaScript
相關(guān)文章:
主站蜘蛛池模板: 男女晚上激烈的拍拍拍免费看 | 西西午夜视频 | 高清不卡日本v在线二区 | 毛片大全免费 | 国产成人久久久精品毛片 | 好大好爽国产美女h福利视频 | 久久亚洲一级α片 | 手机在线观看黄色 | 国产1024在线永久免费观看 | 六月婷婷视频 | 欧美性爽xxxⅹbbbb | 欧美日韩国产高清视频 | 日韩视频免费在线播放 | 国产精品久久久久久久久免费观看 | 成年女人视频播放免费观看 | 嫩模被xxxx视频在线观看 | 中文视频在线 | 国产又色又爽在线观看 | 1024免费看| 色综合久久中文色婷婷 | 在线不卡福利 | 国产99福利视频在线 | 91小视频在线 | 美女黄页在线观看 | 6080午夜一级毛片免费看 | 91久久久久久久 | 亚洲欲色 | 精品一久久 | 亚洲午夜在线观看 | 国产欧美日韩一区二区三区在线 | 欧美大尺度aaa级毛片 | www.久久久 | 日一区二区 | 亚洲成人黄色网 | 欧美特黄a级高清免费大片 欧美特黄a级高清免费看片 | 久久婷婷伊人 | 亚洲精品久 | 国产视频播放 | 久久538 | 亚洲国产成人在线 | 久久久久久综合成人精品 |