Home > Web Front-end > JS Tutorial > body text

Limited range dragging, magnetic adsorption.

巴扎黑
Release: 2017-06-23 11:04:16
Original
1291 people have browsed it

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
body {
margin: 0;
}
#wrap {
margin: 50px auto;
position: relative;
border: 1px solid #000;
width: 600px;
height: 500px;
} 
#div {
position: absolute;
left: 0;
top: 0;
width: 100px;
height: 100px;
background: red;
cursor: move;
}
</style>
</head>
<body>
<div id="wrap">
<div id="div">文字</div>
</div>
<script type="text/javascript">
(function(){
var div = document.querySelector(&#39;#div&#39;);
var maxX = div.offsetParent.clientWidth - div.offsetWidth;
var maxY = div.offsetParent.clientHeight - div.offsetHeight;
div.addEventListener(&#39;mousedown&#39;, function(e) {
e.preventDefault();
var start = {x: e.clientX,y: e.clientY};
var elOffset = {x: div.offsetLeft,y: div.offsetTop};
document.addEventListener(&#39;mousemove&#39;, move);
document.addEventListener(&#39;mouseup&#39;, end);
function move(e){
var dis  = {x:e.clientX - start.x,y:e.clientY - start.y};
var x = dis.x + elOffset.x;
var y = dis.y + elOffset.y;
/* 左侧磁性吸附 */
x = x<0?0:(x>maxX?maxX:x);

y = y<0?0:(y>maxY?maxY:y);
console.log(x);
div.style.left = x + "px";
div.style.top = y + "px";
}
function end(e){
document.removeEventListener(&#39;mousemove&#39;, move);
document.removeEventListener(&#39;mouseup&#39;, end);
var dis  = {x:e.clientX - start.x,y:e.clientY - start.y};
var x = dis.x + elOffset.x;
var y = dis.y + elOffset.y;
/* 左侧磁性吸附 */
x = x<100?0:(x>maxX?maxX:x);
/* 上边磁性吸附 */
y = y<100?0:(y>maxY?maxY:y);
console.log(x);
div.style.left = x + "px";
div.style.top = y + "px";
}
});
})(); 
</script>
</body>
</html>
Copy after login


The above is the detailed content of Limited range dragging, magnetic adsorption.. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!