这是缩放工作示例。我希望图像在图像上的实际鼠标位置上放大。如何做到这一点?没有图书馆。
const image = document.querySelector('img');
const zoom = {
min: 1,
max: 3,
value: 1,
step: 0.1
};
image.addEventListener('wheel', event => {
event.preventDefault();
if (event.deltaY < 0) {
zoom.value = zoom.value >= zoom.max ? zoom.max : zoom.value + zoom.step;
} else if (event.deltaY > 0) {
zoom.value = zoom.value <= zoom.min ? zoom.min : zoom.value - zoom.step;
}
image.style.transform = `scale(${zoom.value})`
}
)
div {
width: 500px;
overflow: hidden;
}
img {
width: 100%;
}
<div>
<img src="https://picjumbo.com/wp-content/uploads/free-stock-photos-san-francisco-1080x720.jpg">
</div>
最佳答案
const image = document.querySelector('img');
const zoom = {
min: 1,
max: 3,
value: 1,
step: 0.1
};
var div = document.querySelector('div');
div.addEventListener('wheel', event => {
event.preventDefault();
if (event.deltaY < 0) {
zoom.value = zoom.value >= zoom.max ? zoom.max : zoom.value + zoom.step;
} else if (event.deltaY > 0) {
zoom.value = zoom.value <= zoom.min ? zoom.min : zoom.value - zoom.step;
}
image.style.transform = `scale(${zoom.value})`
var xPerc = (x * 100) / image.width;
var yPerc = (y * 100) / image.height;
image.style.transformOrigin = xPerc + '%' + ' ' + yPerc + '%';
}
)
var x, y;
div.addEventListener('mousemove', e => {
x = e.clientX - div.offsetLeft;
y = e.clientY - div.offsetTop;
})
div {
width: 500px;
overflow: hidden;
}
img {
width: 100%;
}
<div>
<img src="https://picsum.photos/200">
</div>
试了一下您的示例,发现 transform-origin
可能会成功。添加了相对于图像容器的坐标 x,y,并将它们转换为百分比,以便设置图像的 tranform-origin
样式属性。
关于javascript - 鼠标点缩放图片-滚轮事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58114454/