JS achieve mouse drag effects and zoom

Prevent bubbling event drag a child element of the parent element can not get out, can not exceed the size of the parent element, Zoom In / Out: Requirements

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
*{margin: 0;padding: 0;}
.box1{border: 10px solid #000;width: 400px;height: 400px;position: relative;margin: 0 auto;}
.box2{position: absolute;width: 80px;height: 80px;background: gold;top: 0;left: 0;}
.box3{position: absolute;width: 10px;height: 10px;right: -5px;bottom: -5px;background: #0000FF;border-radius: 50%;}
</style>
</head>
<body>
<div class="box1">
<div class="box2">
<div class="box3"></div>
</div>
</div>
<script type="text/javascript">
var box1 = document.querySelector(".box1");
var box2 = document.querySelector(".box2");
var box3 = document.querySelector(".box3");
box1.onmousedown = function(e) {
e = e || window.event;
var left = box2.offsetLeft;
var top = box2.offsetTop;
var nowX = e.clientX;
var nowY = e.clientY;
document.onmousemove = function(e) {
var resultX = left + e.clientX - nowX;
var resultY = top + e.clientY - nowY;
if(resultX < 0) {
resultX = 0;

} else if (resultX > box1.clientWidth - box2.offsetWidth) {

resultX = box1.clientWidth - box2.offsetWidth
}
if(resultY < 0) {
resultY = 0;
} else if (resultY > box1.clientHeight - box2.offsetHeight) {
resultY = box1.clientHeight - box2.offsetHeight
}
box2.style.left = resultX + "px";
box2.style.top = resultY + "px";
}
}
box3.onmousedown = function(e) {
e = e || window.event;
e.stopPropagation();
e.cancelBubble = true;
var width = box2.offsetWidth;
var height = box2.offsetHeight;
var nowX = e.clientX;
var nowY = e.clientY;
document.onmousemove = function(e) {
e = e || window.event;
var a = width + e.clientX - nowX;
var b = height + e.clientY - nowY;
if(a > box1.clientWidth){
a = box1.clientWidth;
}
if(b > box1.clientHeight){
b = box1.clientHeight;
}
box2.style.width = a + "px"
box2.style.height = b + "px";
}
}
document.onmouseup = function() {
document.onmousemove = null;
}
</script>
</body>
</html>

 

Guess you like

Origin www.cnblogs.com/mizuno0237/p/11443456.html