由于似乎没有办法通过js直接设置浏览器的缩放级别,所以我想重写浏览器缩放并编写自己的代码。
从scale = 1开始时,此代码可以正常工作,但我在已经缩放了一点并将光标移动到图像的另一部分以进一步缩放的情况下遇到了麻烦。这样做时,变焦的焦点总是比预期跳得更远,因为更改变换原点会导致整个图像发生移动。也许设置变换原点不是正确的方法......
var myDiv = document.querySelector(".container");
var img = myDiv.querySelector("img");
var scale = 1.0;
myDiv.addEventListener('wheel', function (ev) {
if(!ev.ctrlKey)
{
return;
}
ev.preventDefault();
const rect = myDiv.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
img.style.transformOrigin = x + "px " + y + "px"
scale += event.deltaY * -0.005;
// Apply scale transform
img.style.transform = `scale(${scale})`;
})
.container {
width: 600px;
height: 200px;
margin: auto;
border: 1px solid gray;
overflow: hidden;
}
img {
width: 100%;
transform: scale(1.0);
}
<div class="container">
<img src="https://picsum.photos/id/200/600/200">
</div>
您可以利用
transform: scale(1.5)
var myDiv = document.querySelector(".container");
var img = myDiv.querySelector("img");
var scale = 1.0
myDiv.addEventListener('mousemove', function(ev) {
const rect = myDiv.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
img.style.transformOrigin = x + "px " + y + "px"
})
myDiv.addEventListener('wheel', function (ev) {
ev.preventDefault();
scale += event.deltaY * -0.001;
// Apply scale transform
img.style.transform = `scale(${scale})`;
})
.container {
width: 600px;
height: 200px;
margin: auto;
border: 1px solid gray;
overflow: hidden;
}
img {
width: 100%;
transform: scale(1.0);
}
<div class="container">
<img src="https://picsum.photos/id/200/600/200">
</div>