需求:实现鼠标滚轮上滚下滚缩放图片,单击不松开拖动图片
给图片添加一个盒子
// dom
<div @mousewheel.prevent="rollImg" class="box">
<img :src="src" class="img" ref="imgDiv" @mousedown="move" />
</div>
methods中的代码:
// script
// 拖动图片
move(e) {
// 阻止默认事件
e.preventDefault();
// 获取元素
var boxDom = document.querySelector(".box");
var img = document.querySelector(".img");
var x = e.pageX - img.offsetLeft;
var y = e.pageY - img.offsetTop;
// 鼠标移动事件
boxDom.addEventListener("mousemove", move);
function move(e) {
img.style.left = e.pageX - x + "px";
img.style.top = e.pageY - y + "px";
}
// 鼠标抬起移除事件
img.addEventListener("mouseup", function () {
boxDom.removeEventListener("mousemove", move);
});
// 鼠标离开移除事件
boxDom.addEventListener("mouseout", function () {
boxDom.removeEventListener("mousemove", move);
});
},
// 缩放图片
rollImg(e) {
let transform = this.$refs.imgDiv.style.transform
let zoom = transform.indexOf("scale") != -1 ? +transform.split("(")[1].split(")")[0] : 1
zoom += e.wheelDelta / 1200
if (zoom > 0.1 && zoom < 5) {
this.$refs.imgDiv.style.transform = "scale(" + zoom + ")"
}
},
CSS样式:
// css
.box {
position: relative;
width: 100%;
height: 360px;
background-color: rgb(147, 145, 145);
// 添加背景图片
background-image: url(../../../assets/img/bg.png);
background-position: 0 0;
float: left;
overflow: hidden;
}
.img {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
max-width: 923px;
max-height: 460px;
cursor: move;
}
效果: