JS实现放大镜效果

时间:2021-01-01 06:28:19
经常浏览淘宝、京东等一些商城网站,都会看到各种各样的页面动态效果图,今天终于花了时间实现了下“放大镜效果”
说起放大镜,无非就是对两张图片的操作,内容相同、大小不同的两张图片,注:小图片的长宽与大图片的长宽成等比例。

用到的主要知识:       offsetLeft:元素相对于父元素的左位移
offSetRight:元素相对于父元素的右位移
offSetWidth:元素所展现出来的宽度(不包括滚动条)
offSetHight:元素所展现出来的高度(不包括滚动条)
event.clientX:元素的X坐标
event.clientY:元素的Y坐标
对象.onmouseover事件
对象.onmouseout事件
对象.onmousemove事件
等比例算法等

不多啰嗦啦!还是直接看代码:
html页面:
<!doctype html>
<html>
<head>
<title>放大镜</title>
<meta charset="utf-8"/>
<link href="css/magnifier.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="js/magnifier.js"></script>
</head>
<body>
<div id="small-box">
<div id="float-box"></div>
<img title="small img" src="images/macbook-small.jpg">
</div>
<div id="big-box">
<img title="bigger img" src="images/macbook-big.jpg">
</div>
</body>
</html>
css脚本:
*{
margin:0px;
padding:0px;
}


#small-box{
position:relative;
border:1px solid #ccc;
display: block;
width: 400px;
height: 255px;
margin: 50px;
}


#float-box{
display: none;
width: 160px;
height: 120px;
position: absolute;
background: #ffffcc;
border: 1px solid #ccc;
filter: alpha(opacity=50);
opacity: 0.5;
}


#big-box {
display: none;
position:absolute;
top:0px;
z-index:1;
left: 460px;
width: 410px;
height: 307px;
overflow: hidden;
border: 1px solid #ccc;
}


#big-box img{
position:absolute;
}
js脚本:
window.onload = function () {
// 获取所需要操作的对象
var smallBox = document.getElementById("small-box");
var floatBox = document.getElementById("float-box");
var bigBox = document.getElementById("big-box");
var bigImage = bigBox.getElementsByTagName("img")[0];

// 鼠标移动到对象上显示放大镜和放大镜放大后的图像
smallBox.onmouseover = function(){
floatBox.style.display = "block";
bigBox.style.display = "block";
}

// 鼠标移出对象时隐藏放大镜和放大镜放大后的图像
smallBox.onmouseout = function(){
floatBox.style.display = "none";
bigBox.style.display = "none";
}

// 鼠标在对象上移动触发的事件
smallBox.onmousemove = function(e){
var event = e || window.event;
var left = event.clientX - smallBox.offsetLeft - floatBox.offsetWidth/2;
var top = event.clientY - smallBox.offsetTop - floatBox.offsetHeight/2;

if(left < 0) {
left = 0;
} else if (left > (smallBox.offsetWidth - floatBox.offsetWidth)) {
left = smallBox.offsetWidth - floatBox.offsetWidth;
}

if (top < 0) {
top = 0;
} else if (top > (smallBox.offsetHeight - floatBox.offsetHeight)) {
top = smallBox.offsetHeight - floatBox.offsetHeight;
}

// 设置放大镜移动的距离
floatBox.style.left = left + "px";
floatBox.style.top = top + "px";
// 根据比例计算放大镜放大后的图像移动的位移(负数)
bigImage.style.left = -(left * bigImage.offsetWidth)/smallBox.offsetWidth + "px";
bigImage.style.top = -(top * bigImage.offsetHeight)/smallBox.offsetHeight + "px";
}
}
图片略,需要实现的童靴们,自己找图片!