放大鏡如何用js
阿新 • • 發佈:2017-09-09
etl ddl url spl none parent att order all
例如:
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