JavaScript 鼠标拖动&缩放元素
直接上代码:
<!doctype html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>鼠标拖动&缩放</title> <style> .onScale { border: 1px dashed gray; } </style> </head> <body> 默认模式下图片可拖动,双击图片可调整图片大小。 <div id="cute" style="position: absolute; width: 266.66px; height: 344.44px; background: url(./cute.png); background-size: 100% 100%;"></div> <script> var cute = document.getElementById('cute'); var x = y = l = t = w = h = 0; var isMove = false; var isScale = isScale2 = false; cute.onmousedown = function(e) { x = e.clientX; y = e.clientY; t = cute.offsetTop; l = cute.offsetLeft; w = cute.clientWidth; h = cute.clientHeight; if(isScale == false) { cute.style.cursor = 'move'; isMove = true; } else { var mx = e.clientX - cute.offsetLeft; var my = e.clientY - cute.offsetTop; isScale2 = 0; if(mx < 15) { isScale2 = 1; } else if(mx > cute.clientWidth - 15) { isScale2 = 2; } else if(my < 15) { isScale2 = 3; } else if(my > cute.clientHeight - 15) { isScale2 = 4; } } } window.onmouseup = function() { if(isMove) { isMove = false; } if(isScale2) { isScale2 = false; } cute.style.cursor = 'default'; } window.onmousemove = function(e) { if(isMove) { var nl = e.clientX - ( x - l ); var nt = e.clientY - ( y - t ); cute.style.left = nl + 'px'; cute.style.top = nt + 'px'; } else if(isScale2) { switch(isScale2) { case 1: var nl = l - (x - e.clientX); var nw = w + (x - e.clientX); cute.style.left = nl + 'px'; cute.style.width = nw + 'px'; break; case 2: var nw = w + (e.clientX - x); cute.style.width = nw + 'px'; break; case 3: var nt = t - (y - e.clientY); var nh = h + (y - e.clientY); cute.style.top = nt + 'px'; cute.style.height = nh + 'px'; break; case 4: var nh = h + (e.clientY - y); cute.style.height = nh + 'px'; break; } } } cute.ondblclick = function(e) { if(isScale) { cute.classList.remove('onScale'); isMove = false; isScale = false; } else { cute.classList.add('onScale'); isScale = true; } } cute.onmousemove = function(e) { if(isScale == false) { return; } var mx = e.clientX - cute.offsetLeft; var my = e.clientY - cute.offsetTop; if(mx < 15 || mx > cute.clientWidth - 15) { cute.style.cursor = 'w-resize'; } else if(my < 15 || my > cute.clientHeight - 15) { cute.style.cursor = 's-resize'; } else { cute.style.cursor = 'default'; } } </script> </body> </html>
另外分享代码中用到的"cute.png",图源不明,是从同事那要来的:
欢迎转载,转载时请注明来源。