js实现剪切 曾经终败给现在 2021-09-02 05:24 223阅读 0赞 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style type="text/css"> * { margin: 0; padding: 0; } #box { position: relative; width: 430px; height: 430px; margin: 0 auto; border: 1px solid red; background-image: url(images/small.jpg); } #box .mask { position: absolute; width: 100%; height: 100%; background-color: rgba(0, 0, 0, .5); left: 0; top: 0; } #area { position: absolute; width: 150px; height: 150px; background-image: url(images/small.jpg); left: 0; top: 0; } #area #dot { position: absolute; width: 10px; height: 10px; right: -5px; bottom: -5px; background-color: red; border-radius: 50%; } </style> </head> <body> <div id="box"> <div class="mask"></div> <div id="area"> <div id="dot"></div> </div> </div> <script type="text/javascript"> // 获取元素 var box = document.getElementById("box"); var dot = document.getElementById("dot"); var area = document.getElementById("area"); // 给dot添加mousedown事件 dot.onmousedown = function(e) { // 阻止冒泡的方式 e.stopPropagation(); // 获取鼠标位于视口中的位置 var x = e.clientX; var y = e.clientY; // 获取area的宽度和高度 var a_width = area.clientWidth; var a_height = area.clientHeight; // console.log(a_width, a_height); // 给document添加mousemove事件 document.onmousemove = function(e) { // 获取鼠标移动之后的距离 var m_x = e.clientX; var m_y = e.clientY; // 定义变量用于简化书写 var resultX = m_x - x + a_width; var resultY = m_y - y + a_height; // 边界限制 if (resultX < 0) { resultX = 0; } else if (resultX > box.clientWidth - area.offsetLeft) { resultX = box.clientWidth - area.offsetLeft; } if (resultY < 0) { resultY = 0; } else if (resultY > box.clientHeight - area.offsetTop) { resultY = box.clientHeight - area.offsetTop; } // 赋值给area的宽度和高度 area.style.width = resultX + "px"; area.style.height = resultY + "px"; } } // 为area绑定mousedown事件 area.onmousedown = function(e) { // 获取鼠标位于视口中的位置 var x = e.clientX; var y = e.clientY; // 获取元素的定位值 var a_left = this.offsetLeft; var a_top = this.offsetTop; // 给document添加mousemove事件 document.onmousemove = function(e) { // 获取鼠标移动后的位置 var a_x = e.clientX; var a_y = e.clientY; // 定义变量用于简化书写 var resultX = a_x - x + a_left; var resultY = a_y - y + a_top; // 改变area的定位值 area.style.left = resultX + "px"; area.style.top = resultY + "px"; // 改变area中图片的背景定位 area.style.backgroundPosition = -resultX + "px " + -resultY + "px"; } } // 当鼠标抬起的时候, 取消掉onmousemove事件 document.onmouseup = function() { document.onmousemove = null; } </script> </body> </html>
还没有评论,来说两句吧...