思路
-
获取需要的标签
-
监听鼠标进去的事件:2.1:鼠标进入光标和大图显示
2.2:取鼠标的坐标 (offsetLeft和offsetHeight)
2.3:鼠标的位置应该在光标的中间位置
2.4:边界处理(超出范围)
2.5: 按比例缩放 (公式:smllX / bigX = small.box.width / big.box.width; -
监听鼠标离开:让光标和大图隐藏
-
遍历下面的一排:4.1求出单个的img
4.2监听点击Img事件
4.3改变大图和小图的图片地址
<script>
window.onload = function (){
//1.获取需要的标签
var box = document.getElementById("box");
var small_box = box.children[0];
var mask = small_box.children[1];
var small_img = small_box.children[0];
var big_box = box.children[1];
var big_img = big_box.children[0];
var list_img = document.getElementById("list").children;
//2.监听事件
small_box.onmouseover = function (){
//2.1让隐藏的显现出来
mask.style.display = "block";
big_box.style.display = "block";
//2.2监听鼠标的进入
small_box.onmousemove = function (event){
var event = event || window.event;
//2.2.1 鼠标的坐标
var pointX = event.clientX - box.offsetLeft - mask.offsetWidth * 0.5;
var pointY = event.clientY - box.offsetTop - mask.offsetHeight * 0.5;
//2.2.2 判断边界位置
if(pointX < 0){
pointX = 0;
}else if(pointX >= small_box.offsetWidth - mask.offsetWidth){
pointX = small_box.offsetWidth - mask.offsetWidth;
};
if(pointY < 0){
pointY = 0;
}else if(pointY >= small_box.offsetHeight - mask.offsetHeight){
pointY = small_box.offsetHeight - mask.offsetHeight;
};
//2.2.3 放大镜的位置
mask.style.left = pointX + 'px';
mask.style.top = pointY + 'px';
//2.2.4让大图移动
/*
公式:
smllX / bigX = small.box.width / big.box.width;
bigX = smllX /(small.box.width / big.box.width)
*/
big_img.style.left = -pointX /(small_box.offsetWidth / big_box.offsetWidth) + 'px';
big_img.style.top = -pointY /(small_box.offsetHeight / big_box.offsetHeight) + 'px';
}
};
//3.监听鼠标离开
small_box.onmouseout = function (){
//2.1恢复隐藏
mask.style.display = "none";
big_box.style.display = "none";
}
//4.遍历图片
for(var i = 0; i < list_img.length; i++){
(function(i){
var img = list_img[i];
img.onmouseover = function (){
//改变大图和小图的位置
small_img.src = "img/pic00"+(i+1)+".jpg";
big_img.src = 'img/pic0'+(i+1)+'.jpg';
}
})(i);
}
}
</script>
路还远,加油啊