原生js拖拽实现图形伸缩效果
crazy的蓝色梦想 人气:0本文实例为大家分享了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; } .div1{ width: 200px; height: 200px; background-color: #71e4ff; position: absolute; top: 200px; left: 200px; } .t, .b{ width: 100%; height: 20px; background-color:#ffa2d3; position: absolute; } .t{ left: 0; top:0; } .b{ left: 0; bottom:0; } .r, .l{ width: 20px; height: 100%; background-color:#ffa2d3; position: absolute; } .r{ right: 0; top:0; } .l{ left: 0; top:0; } .lt, .lb, .rt, .rb{ width: 20px; height: 20px; background-color: #93ff6b; position: absolute; } .lt{ left: 0; top:0; } .rt{ right: 0; top:0; } .lb{ left: 0; bottom: 0; } .rb{ right: 0; bottom:0; } </style> </head> <body> <div class="div1" id="_div1"> <div class="t"></div> <div class="r"></div> <div class="b"></div> <div class="l"></div> <div class="lt"></div> <div class="lb"></div> <div class="rt"></div> <div class="tb"></div> </div> </body> </html> <script> // 获取元素 var _div1 = document.getElementById("_div1"); var divs = _div1.children; // 遍历每个可以拖拽的元素 for(var i = 0;i < divs.length ;i++) { drag(divs[i]); } // 封装一个拖拽函数 function drag(obj){ obj.onmousedown = function(event){ // 捕获事件 var event = event || window.event; // 存储当前的_div1的宽高 var divW = _div1.offsetWidth; var divH = _div1.offsetHeight; // 获得当前_div1的offsetLeft 和 offsetTop var divL = _div1.offsetLeft; var divT = _div1.offsetTop; // 存储鼠标按下时的位置 var clientx = event.clientX; var clienty = event.clientY; document.onmousemove = function(event){ var event = event || window.event; if(obj.className.indexOf('t') != -1){ _div1.style.height = divH + ( clienty- event.clientY) + 'px'; _div1.style.top = divT -( clienty- event.clientY)+ 'px'; } if(obj.className.indexOf('b') != -1){ _div1.style.height = divH + ( event.clientY -clienty ) + 'px'; } if(obj.className.indexOf('r')!= -1){ _div1.style.width = divW + ( event.clientX - clientx) + 'px'; } if(obj.className.indexOf('l')!= -1){ _div1.style.width = divW + ( clientx - event.clientX) + 'px'; _div1.style.left = event.clientX + 'px'; } } document.onmouseup = function(){ document.onmousemove = null; document.onmouseup = null; } } return false; } </script>
加载全部内容