看一下最終效果,圖片可以拖動,可以縮放
把代碼貼出來,可以直接粘貼使用,大致的思想就是鼠標按下的時候獲取當時的鼠標位置,要減去left和top值,移動的時候獲取位置減去初始的值就得到移動的時候的left和top值
<!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> #box { width: 100px; height: 100px; background-color: aquamarine; position: absolute; } #father { width: 600px; height: 500px; background-color: rgb(226, 117, 184); position: relative; } img { width: 100%; height: 100%; cursor: move; } #scale { width: 10px; height: 10px; overflow: hidden; cursor: se-resize; position: absolute; right: 0; bottom: 0; background-color: rgb(122, 191, 238); } </style> </head> <body> <div id="father"> <div id="box"> <img src="http://img4.imgtn.bdimg.com/it/u=4245161611,1195625695&fm=27&gp=0.jpg"/> <div id="scale"></div> </div> </div> <script type="text/javascript"> // box是裝圖片的容器,fa是圖片移動縮放的范圍,scale是控制縮放的小圖標 var box = document.getElementById("box"); var fa = document.getElementById('father'); var scale = document.getElementById("scale"); // 圖片移動效果 box.onmousedown=function(ev) { var oEvent = ev; // 瀏覽器有一些圖片的默認事件,這里要阻止 oEvent.preventDefault(); var disX = oEvent.clientX - box.offsetLeft; var disY = oEvent.clientY - box.offsetTop; fa.onmousemove=function (ev) { oEvent = ev; oEvent.preventDefault(); var x = oEvent.clientX -disX; var y = oEvent.clientY -disY; // 圖形移動的邊界判斷 x = x <= 0 ? 0 : x; x = x >= fa.offsetWidth-box.offsetWidth ? fa.offsetWidth-box.offsetWidth : x; y = y <= 0 ? 0 : y; y = y >= fa.offsetHeight-box.offsetHeight ? fa.offsetHeight-box.offsetHeight : y; box.style.left = x + 'px'; box.style.top = y + 'px'; } // 圖形移出父盒子取消移動事件,防止移動過快觸發鼠標移出事件,導致鼠標彈起事件失效 fa.onmouseleave = function () { fa.onmousemove=null; fa.onmouseup=null; } // 鼠標彈起后停止移動 fa.onmouseup=function() { fa.onmousemove=null; fa.onmouseup=null; } } // 圖片縮放效果 scale.onmousedown = function (e) { // 阻止冒泡,避免縮放時觸發移動事件 e.stopPropagation(); e.preventDefault(); var pos = { 'w': box.offsetWidth, 'h': box.offsetHeight, 'x': e.clientX, 'y': e.clientY }; fa.onmousemove = function (ev) { ev.preventDefault(); // 設置圖片的最小縮放為30*30 var w = Math.max(30, ev.clientX - pos.x + pos.w) var h = Math.max(30,ev.clientY - pos.y + pos.h) // console.log(w,h) // 設置圖片的最大寬高 w = w >= fa.offsetWidth-box.offsetLeft ? fa.offsetWidth-box.offsetLeft : w h = h >= fa.offsetHeight-box.offsetTop ? fa.offsetHeight-box.offsetTop : h box.style.width = w + 'px'; box.style.height = h + 'px'; // console.log(box.offsetWidth,box.offsetHeight) } fa.onmouseleave = function () { fa.onmousemove=null; fa.onmouseup=null; } fa.onmouseup=function() { fa.onmousemove=null; fa.onmouseup=null; } } </script> </body> </html>
我畫了一張圖,來標識每次鼠標移動,圖片定位left和top的計算
最近在圖片移動的基礎上寫了一個可以隨鼠標移動旋轉,拉伸的案例,增加了圖片旋轉功能,實現方式相對復雜些,有這個需求的可以看我這篇博客https://www.cnblogs.com/steamed-twisted-roll/p/13408245.html