电商网站的放大镜功能
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了电商网站的放大镜功能相关的知识,希望对你有一定的参考价值。
首先是样式部分,分别定义一大一小两个盒子,用来盛放大图片和小图片。
<style >
*{
padding: 0;
margin: 0;
}
#demo {
display: block;
width: 400px;
height: 255px;
margin: 50px;
position: relative;
border: 1px solid #ccc;
}
#small_box {
position: absolute;
z-index: 1;
}
#mark {
position: absolute;
display: block;
width: 400px;
height: 255px;
background-color: #fff;
filter: alpha(opacity=0);/*兼容IE*/
opacity: 0;
z-index: 10;
}
#float_box {
display: none;
width: 160px;
height: 120px;
position: absolute;
background-color: #ffffcc;
border: 1px solid #ccc;
opacity: 0.5;
filter: alpha(opacity=50);
cursor: move;
}
#big_box {
display: none;
position: absolute;
top: 0;
left: 460px;
width: 400px;
height: 300px;
overflow: hidden;
border:1px solid #ccc;
z-index: 1;
}
#big_box img {
position: absolute;
z-index: 5;
}
</style>
之后就是脚本部分:
1.首先分别取得各个元素
2.为小盒子添加鼠标事件
3.计算鼠标在小盒子的位移,大盒子里的图片进行相反方向的位移即可
<script>
window.onload = function(){
function getId(id) {
return document.getElementById(id);
}
var objDemo = getId("demo");
var objSmallBox = getId("small_box");
var objMark = getId("mark");
var objFloatBox = getId("float_box");
var objBigBox = getId("big_box");
var objBigImg = objBigBox.getElementsByTagName("img")[0];
objMark.onmouseover = function() {
objFloatBox.style.display = "block";
objBigBox.style.display = "block";
}
objMark.onmouseout = function() {
objFloatBox.style.display = "none";
objBigBox.style.display = "none";
}
objMark.onmousemove = function (e) {
var _event = e || window.event;
var left = _event.clientX - objDemo.offsetLeft - objSmallBox.offsetLeft - objFloatBox.offsetWidth / 2;
var top = _event.clientY - objDemo.offsetTop - objSmallBox.offsetTop - objFloatBox.offsetHeight / 2;
var objSmaWid = objMark.offsetWidth - objFloatBox.offsetWidth;
var objSmaHgt = objMark.offsetHeight - objFloatBox.offsetHeight;
//限制小盒子中显示框的范围
if(left < 0) {
left = 0;
}else if(left > objSmaWid) {
left = objSmaWid;
}
if(top < 0) {
top = 0;
}else if (top > objSmaHgt) {
top = objSmaHgt;
}
objFloatBox.style.left = left + "px";
objFloatBox.style.top = top + "px";
//主要使用公式 A/B = C/D
var percentX = left/objSmaWid;
var percentY = top/objSmaHgt;
var objBigWid = objBigImg.offsetWidth - objBigBox.offsetWidth;
var objBigHgt = objBigImg.offsetHeight - objBigBox.offsetHeight;
objBigImg.style.left = -percentX * objBigWid + "px";
objBigImg.style.top = -percentY * objBigHgt + "px";
}
}
</script>
结构部分,在#demo中分别设置一大一小两个盒子
<body>
<div id="demo">
<div id="small_box">
<div id="mark"></div> <!--兼容IE-->
<div id="float_box"></div>
<img src="small.jpg" alt="img">
</div>
<div id="big_box">
<img src="big.jpg" alt="bg-img">
</div>
</div>
</body>
</html>
以上是关于电商网站的放大镜功能的主要内容,如果未能解决你的问题,请参考以下文章