实现效果:
JS(核心代码)
1.定义全局缩放值
let scale = 1;
2.获取img标签以及盒子的实例
let scale = 1; // +++++++++++ const imgBox = document.getElementById("imgBox"); const img = document.getElementById("img");
3.实现图片的缩放效果
// 缩放效果(wheel--鼠标滚轮事件) img.addEventListener("wheel", (e) => { // 大于0:滚轮向上滚动 小于0:滚轮向下滚动 if (e.wheelDelta > 0) { scale += 0.5; img.style.transform = `scale(${scale})`; } else { if (scale == 1) { img.style.left = 0 + "px"; img.style.top = 0 + "px"; } // 缩放值大于1时,可以缩小,反之亦然 if (scale > 1) { scale -= 0.5; img.style.transform = `scale(${scale})`; } } })
4. 实现图片的拖拽效果
// 拖拽效果 img.onmousedown = function (e) { // 获取鼠标按下时的值 let left = this.offsetLeft; let top = this.offsetTop; let startX = e.clientX; let startY = e.clientY; // 给盒子添加鼠标移动事件,获取移动后视口的值 imgBox.onmousemove = function (event) { // 获取鼠标移动时的值,并更新图片绝对定位的值 img.style.left = event.clientX - startX + left + "px"; img.style.top = event.clientY - startY + top + "px"; } }
5.鼠标左键抬起后,清楚盒子的移动事件
// 鼠标抬起,清除移动事件 document.addEventListener("mouseup", () => { imgBox.onmousemove = null; // 清除move事件 })
HTML代码
创建图片盒子以及图片标签
<div class="imgBox" id="imgBox">
<img src="./06.jpg" alt="" id="img" draggable="false" />
</div>
- draggable="false" 取消img自带的图片拖拽效果
CSS代码
body {
box-sizing: border-box;
}
.imgBox {
position: relative;
width: 1200px;
height: 800px;
border: 2px solid red;
overflow: hidden;
}
.imgBox img {
position: absolute;
width: 100%;
height: 100%;
cursor: pointer;
}