放大镜如何用js

Posted 林水

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了放大镜如何用js相关的知识,希望对你有一定的参考价值。

例如:

let imgs = {
small: ["imgA_1.jpg", "imgB_1.jpg", "imgC_1.jpg"],
middle: ["imgA_2.jpg", "imgB_2.jpg", "imgC_2.jpg"],
large: ["imgA_3.jpg", "imgB_3.jpg", "imgC_3.jpg"]
};

handleSmall();
handleMiddle();
handleMove();



function handleSmall(){
// 渲染小图
smallImg.innerhtml = imgs.small.map((item, index) => {
return `<li><a href="#"><img src="./images/${item}" _id="${index}" class="imgLi" /></a></li>`
}).join("");

smallImg.addEventListener("mouseover", (e) => {
if(e.target.nodeName === "IMG"){

let imgArr = document.getElementsByClassName("imgLi");
for(let i = 0;i < imgArr.length;i++){
imgArr[i].style.borderColor = "transparent";
}
e.target.style.borderColor = "black";

let i = e.target.getAttribute("_id");
middleImg.style.background = `url("./images/${imgs.middle[i]}") no-repeat`;
largeImg.style.background = `url("./images/${imgs.large[i]}") no-repeat`;
}
}, false);
}

function handleMiddle(){
middleImg.addEventListener("mouseover", () => {
largeImg.style.display = "block";
enlarge.style.display = "block";
}, false)
middleImg.addEventListener("mouseout", () => {
largeImg.style.display = "none";
enlarge.style.display = "none";
}, false)
}

function handleMove(){
middleImg.addEventListener("mousemove", (e) => {
// 鼠标相对于文档显示区的坐标
let mouseX = e.clientX;
let mouseY = e.clientY;
// middleImg 相对于文档显示区的坐标
let middleX = middleImg.offsetLeft;
let middleY = middleImg.offsetTop;

let moveX = mouseX - middleX - enlarge.offsetWidth / 2;
let moveY =mouseY -middleY - enlarge.offsetHeight / 2;

if(moveX <= 0){
moveX = 0;
}else if(moveX >= middleImg.clientWidth - enlarge.offsetWidth){
moveX = middleImg.clientWidth - enlarge.offsetWidth
}
if(moveY <= 0){
moveY = 0;
}else if(moveY >= middleImg.clientHeight - enlarge.offsetHeight){
moveY = middleImg.clientHeight - enlarge.offsetHeight
}

enlarge.style.left = moveX + "px";
enlarge.style.top = moveY + "px";

largeImg.style.backgroundPositionX = -moveX * (800 / 430) + "px";
largeImg.style.backgroundPositionY = -moveY * (800 / 430) + "px";

}, false)
}











































































以上是关于放大镜如何用js的主要内容,如果未能解决你的问题,请参考以下文章

如何用Three.js改变CubeGeometry的宽度?

如何用js实现给某个文本框赋值?

如何用 ViewPager 中的另一个片段替换 Android 片段?

如何用opencv python实现图像的局部放大

如何用JS点击超链接弹出对话框

js用面向对象的方法编写放大镜