JS实现鼠标拖拽效果以及放大缩小
Posted mizuno0237
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS实现鼠标拖拽效果以及放大缩小相关的知识,希望对你有一定的参考价值。
要求:拖拽的子元素不能走出父元素,大小不能超过父元素,放大/缩小时阻止冒泡事件
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <style> *margin: 0;padding: 0; .box1border: 10px solid #000;width: 400px;height: 400px;position: relative;margin: 0 auto; .box2position: absolute;width: 80px;height: 80px;background: gold;top: 0;left: 0; .box3position: 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>
以上是关于JS实现鼠标拖拽效果以及放大缩小的主要内容,如果未能解决你的问题,请参考以下文章