js实现限定区域范围拖拉拽效果
编程学习 2021-07-04 14:07www.dzhlxh.cn编程入门
这篇文章主要为大家详细介绍了js实现限定区域范围拖拉拽,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
本文实例为大家分享了js实现限定区域范围拖拉拽的具体代码,供大家参考,具体内容如下
需要在范围内拖拉拽,之前看来许多资料觉得都不是特别满足要求,今天自己写了一个,通过监听鼠标按下、鼠标抬起、鼠标移动事件来控制
代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
#drag {
background: aqua;
width: 200px;
height: 200px;
position: absolute;
-moz-user-select: none;
-khtml-user-select: none;
user-select: none;
}
#parent {
position: relative;
background: #cde4dc;
height: 80vh;
overflow: hidden;
}
</style>
</head>
<body>
<section id="parent">
<div id="drag"><div>这是一个测试</div></div>
</section>
<script type="text/javascript">
//自执行函数,需要拖拽的元素需要设置position:absolute,父元素position:relative
//有传父亲节点、若无则默认body为父节点
((parent, children, mouseType) => {
if (!children) return;
let childrenDiv = document.querySelector(children);
childrenDiv.style.position = 'absolute';
let parentDiv = parent
? document.querySelector(parent)
: document.querySelector('body');
let isDown = false;
let x,
y,
l,
t = 0;
childrenDiv.onmousedown = function (e) {
x = e.clientX;
y = e.clientY;
// 获取左部和底部的偏移量
l = childrenDiv.offsetLeft;
t = childrenDiv.offsetTop;
isDown = true;
childrenDiv.style.cursor = mouseType || 'move';
};
// 鼠标移动
window.onmousemove = function (e) {
if (!isDown) {
return;
}
//获取移动后的x和y坐标
let nx = e.clientX;
let ny = e.clientY;
//获取父元素的宽高
let parentWidth = parentDiv.clientWidth;
let parentHeight = parentDiv.clientHeight;
//获取子元素的宽高
let childrenWidth = childrenDiv.clientWidth;
let childrenHight = childrenDiv.clientHeight;
// 计算移动后的左偏移量和顶部偏移量
let nLeft = nx - (x - l);
let nTop = ny - (y - t);
let nRight = nLeft + childrenWidth;
let nBottom = nTop + childrenHight;
nLeft = nLeft <= 0 ? 0 : nLeft; //判断左边距离是否越界
nTop = nTop <= 0 ? 0 : nTop; //判断上边距离是否越界
//判断右边距离大于父元素宽度
if (nRight >= parentWidth) {
nLeft = parentWidth - childrenHight;
}
// 判断下边界是否越界
if (nBottom >= parentHeight) nTop = parentHeight - childrenHight;
childrenDiv.style.left = nLeft + 'px';
childrenDiv.style.top = nTop + 'px';
};
// 鼠标抬起事件
document.onmouseup = function (e) {
//鼠标抬起
isDown = false;
childrenDiv.style.cursor = 'default';
};
})('#parent', '#drag', 'move');
</script>
</body>
</html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持狼蚁SEO。
编程语言
- Win10 PC创意者更新慢速版15048改进内容与已知问题
- 用纯CSS3实现网页中常见的小箭头
- 神舟笔记本问题集锦
- Bellnames常用操作说明
- 揭秘手机淘宝搜索排序的影响因素
- XHTML入门学习教程-网页Head和DTD
- 笔记本光驱保养常用知识
- hzhost虚拟主机系统致命漏洞
- 电脑无线网络出现红色叉叉无线网卡打不开的六
- 16项评比不得不看 机箱哪些功能最实用
- AI怎么绘制一个呲牙的qq表情-
- 红帽指点杆机械键盘 TEX Yoda上手体验测评
- 笔记本电脑保养常识有哪些-笔记本保养常识总结
- cdr怎么设计圆角矩形效果的图标-
- 在XSLT样式表中声明命名空间小结
- Fireworks教程-常用操作技巧总结