我是JS的新人。
https://codepen.io/Maartinshh/pen/VbGOvm
这是我的代码:
HTML
<img id="imgZoom" width="200px" height="200px" onmousemove="zoomIn(event)" onmouseout="zoomOut()" src="https://media.licdn.com/mpr/mpr/shrink_200_200/AAEAAQAAAAAAAA20AAAAJDZhZjAwOTE3LTExMDQtNDE5OC05NDdhLWUxYTU0ODJiZTdkYQ.png">
<div id="overlay" onmousemove="zoomIn(event)"></div>
CSS
#overlay {
border: 1px solid black;
width: 450px;
height: 450px;
position: absolute;
display: inline-block;
background-image: url('https://media.licdn.com/mpr/mpr/shrink_200_200/AAEAAQAAAAAAAA20AAAAJDZhZjAwOTE3LTExMDQtNDE5OC05NDdhLWUxYTU0ODJiZTdkYQ.png');
background-repeat: no-repeat;
}
JS
function zoomIn(event) {
var element = document.getElementById("overlay");
element.style.display = "inline-block";
var img = document.getElementById("imgZoom");
var posX = event.offsetX ? (event.offsetX) : event.pageX - img.offsetLeft;
var posY = event.offsetY ? (event.offsetY) : event.pageY - img.offsetTop;
element.style.backgroundPosition = (-posX * 1) + "px " + (-posY * 1) + "px";
}
function zoomOut() {
var element = document.getElementById("overlay");
element.style.display = "none";
}
出现问题:如果你看到,那么当我鼠标悬停在左侧的图片时,右侧(缩放)图片,并没有真正跟随缩放。我做错了什么?
另外,如何更改缩放级别(缩放更近)?
提前致谢。
答案 0 :(得分:0)
您需要进行一些计算以添加额外的偏移量以将img放置在div的中心
var offY = (element.clientHeight -img.clientHeight)/2;
var offX = (element.clientWidth -img.clientWidth)/2;
已编辑codepen here