码迷,mamicode.com
首页 > Web开发 > 详细

放大镜如何用js

时间:2017-09-09 14:34:15      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:mouseover   clientx   function   ref   list   dev   else   相对   pre   

例如:

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

标签:mouseover   clientx   function   ref   list   dev   else   相对   pre   

原文地址:http://www.cnblogs.com/langwo/p/7498070.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!