国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

js實現磁性吸附的示例

瀏覽:105日期:2024-04-14 15:35:39

磁性吸附

目錄

代碼實例 與限定范圍拖拽的差異 下載源碼鏈接

代碼實例

* { padding: 0; margin: 0;}#box1 { width: 500px; height: 500px; background: #999; position: relative; left: 100px; top: 100px;}#box { width: 100px; height: 100px; background: #334; position: absolute; cursor: move;}<div id='box1'><div id='box'></div></div>(function () { var dragging = false var boxX, boxY, mouseX, mouseY, offsetX, offsetY var box = document.getElementById(’box’) var box1 = document.getElementById(’box1’) // 鼠標按下的動作 box.onmousedown = down // 鼠標的移動動作 document.onmousemove = move // 釋放鼠標的動作 document.onmouseup = up // 鼠標按下后的函數,e為事件對象 function down(e) { dragging = true // 獲取元素所在的坐標 boxX = box.offsetLeft boxY = box.offsetTop // 獲取鼠標所在的坐標 mouseX = parseInt(getMouseXY(e).x) mouseY = parseInt(getMouseXY(e).y) // 鼠標相對元素左和上邊緣的坐標 offsetX = mouseX - boxX offsetY = mouseY - boxY } // 鼠標移動調用的函數 function move(e){ if (dragging) { // 獲取移動后的元素的坐標 var x = getMouseXY(e).x - offsetX var y = getMouseXY(e).y - offsetY // 計算可移動位置的大小, 保證元素不會超過可移動范圍 // 此處就是父元素的寬度減去子元素寬度 var width = box1.clientWidth - box.offsetWidth var height = box1.clientHeight - box.offsetHeight // min方法保證不會超過右邊界,max保證不會超過左邊界 x = Math.min(Math.max(0, x), width) y = Math.min(Math.max(0, y), height) // 磁性吸附部分 if (x < RANGE) {x = 0} if (width - x < RANGE) {x = width} if (y < RANGE) {y = 0} if (height - y < RANGE) {y = height} // 給元素及時定位 box.style.left = x + ’px’ box.style.top = y + ’px’ } } // 釋放鼠標的函數 function up(e){ dragging = false } // 函數用于獲取鼠標的位置 function getMouseXY(e){ var x = 0, y = 0 e = e || window.event if (e.pageX) { x = e.pageX y = e.pageY } else { x = e.clientX + document.body.scrollLeft - document.body.clientLeft y = e.clientY + document.body.scrollTop - document.body.clientTop } return { x: x, y: y } }})()

與限定范圍拖拽的差異

簡易拖拽的鏈接

限定范圍拖拽的鏈接

添加磁性吸附部分

// 磁性吸附部分if (x < RANGE) {x = 0}if (width - x < RANGE) {x = width}if (y < RANGE) {y = 0}if (height - y < RANGE) {y = height}

下載源碼鏈接

星輝的Github

以上就是js實現磁性吸附的示例的詳細內容,更多關于js實現磁性吸附的資料請關注好吧啦網其它相關文章!

標簽: JavaScript
相關文章:
主站蜘蛛池模板: 静海县| 竹山县| 新丰县| 林甸县| 丰台区| 荥经县| 固始县| 宕昌县| 泰安市| 岳普湖县| 丽江市| 苍南县| 乌鲁木齐县| 汉中市| 监利县| 女性| 乌兰浩特市| 木兰县| 博野县| 日照市| 怀化市| 桐乡市| 正宁县| 凤阳县| 定结县| 峨山| 宜阳县| 万宁市| 武山县| 衡水市| 霍城县| 酉阳| 西盟| 东兴市| 平江县| 连云港市| 望奎县| 天水市| 鹤庆县| 游戏| 平乡县|