本文主要是介绍代码实现拖拽及吸附功能,具体要求如下,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
代码实现拖拽及吸附功能,具体要求如下:
- 两个绿色方块作为盒子,一个红色方块作为可拖拽方块;
- 红块可从上方盒子拖拽到下方盒子中;
- 拖拽结束后,红块被吸附到其所在盒子中距离最近的角上。
<!doctype html>
<html>
<head><meta charset="utf-8"><title></title><style>body {margin: 0;padding: 0;background: black;}.div {width: 120px;height: 120px;background: gray;}#div2 {margin-top: 20px;}#drag {background-color: red;position: absolute;width: 50px;height: 50px;}</style></head><body><div id="div1" class="div"><div id="drag"></div></div><div id="div2" class="div"></div><script type="text/javascript">let drag = document.querySelector('#drag')let div1 = document.getElementById('div1')let div2 = document.getElementById('div2')// 记录div1和div2分别距离屏幕的位置let div1_top = div1.getBoundingClientRect().toplet div1_left = div1.getBoundingClientRect().leftlet div2_top = div2.getBoundingClientRect().toplet div2_left = div2.getBoundingClientRect().left// div1和div2所包裹的x,y的取值范围let allow_div1 = [div1_left, div1_left + div1.offsetWidth, div1_top, div1.offsetHeight]let allow_div2 = [div2_left, div2_left + div2.offsetWidth, div2_top, div2_top + div2.offsetHeight]drag.onmousedown = function (e) {// 当鼠标移动时给drag确定位置document.onmousemove = function (e) {drag.style.top = `${e.clientY}px`;drag.style.left = `${e.clientX}px`;}document.onmouseup = function (e) {document.onmousemove = null;document.onmouseup = null;let isputout = true// 当鼠标抬起时判断方块所在的位置if (e.clientX >= allow_div2[0] && e.clientX <= allow_div2[1]) {if (e.clientY >= allow_div2[2] && e.clientY <= allow_div2[3]) {drag.style.left = `${allow_div2[0]}px`;drag.style.top = `${allow_div2[2]}px`;isputout = false}}// 若没有放入放回原位if (isputout) {drag.style.left = `${allow_div1[0]}px`;drag.style.top = `${allow_div1[2]}px`;}}return false;}</script>
</body>
</html>
这篇关于代码实现拖拽及吸附功能,具体要求如下的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!