js实现拖拽和吸附代码分享

小云云
小云云 原创
2018-03-02 13:57:57 1410浏览

本文主要和大家分享js实现拖拽和吸附代码,希望能帮助到大家。

<!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>
* {
padding: 0;
margin: 0;
}
#big {
width: 500px;
height: 500px;
background-color: #ccc;
position: relative
}
#box {
width: 100px;
height: 100px;
background-color: #f00;
position: absolute
}
</style>
<script>
window.onload = function () {
var box = document.getElementById('box');
var big = document.getElementById('big');
// 鼠标在box中的位置
var disX = 0,
disY = 0;
box.onmousedown = function (e) {
var thisE = e || event;
disX = thisE.clientX - box.offsetLeft;
disY = thisE.clientY - box.offsetTop;
document.onmousemove = function (ev) {
var thisEvent = ev || event;
var l = thisEvent.clientX - disX;
var t = thisEvent.clientY - disY;
if (l < 20) {
l = 0;
} else if (l > big.offsetWidth - box.offsetWidth - 20) {
l = big.offsetWidth - box.offsetWidth;
}
if (t < 20) {
t = 0;
} else if (t > big.offsetHeight - box.offsetHeight - 20) {
t = big.offsetHeight - box.offsetHeight;
}
box.style.left = l + 'px';
box.style.top = t + 'px';
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
}
}
e.preventDefault();
}
}
</script>
</head>
<body>
<p id="big">
<p id="box"></p>
</p>
</body>
</html>

相关推荐:

js代码实现鼠标拖拽div实例

js控制文件拖拽及获取拖拽内容

限制范围拖拽,磁性吸附。

以上就是js实现拖拽和吸附代码分享的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。