1、html样式如下:
<div id="small-container">
<span id="cover"></span>
<span id="float"></span>
<img id="smallImage" src="" />
</div>
<div id="big-container">
<img src="">
</div>
重点样式注释:
[small-container],[big-container]:图片容器。
[cover]:用来覆盖整个图片,主要是作用于鼠标事件。如果是在图片容器内的图片上使用鼠标事件,会造成float层一直闪烁,重复触发鼠标事件
[float]:漂浮层。
2、css 样式如下:
#small-container{
width: 300px;
height: 300px;
position: relative;
z-index: 1;
}
#small-container img{
width: 100%;
height: 100%;
}
#cover{
display: block;
width: 300px;
height: 300px;
position: absolute;
opacity: 1;
z-index: 10;
}
#float{
display: none;
width: 100px;
height: 100px;
position: absolute;
background-color: rgba(250,250,250,0.6);
filter: alpha(opacity=50);
opacity: 50%;
cursor: move;
opacity: 0.5;
z-index: 1;
}
#big-container{
width:400px;
height: 400px;
display: none;
position: absolute;
left: 350px;
top: 0;
border: 1px solid black;
overflow: hidden;
z-index: 1;
}
#big-container img{
position: absolute;
z-index: 5;
}
重点样式注释:
[overflow]:隐藏超出父级div的部分,实现显示部分图片。
[filter]:过滤器,css3样式。
[z-index]:主要用来确定上下分层。
3、js代码如下:
window.onload=function(){
var smallContainer=document.getElementById('small-container');
var cover=document.getElementById('cover');
var float=document.getElementById('float');
var bigContainer=document.getElementById('big-container');
var image=bigContainer.getElementsByTagName('img');
// 鼠标移入事件
cover.onmouseover=function()
{
float.style.display="block";
bigContainer.style.display="block";
}
// 鼠标移出事件
cover.onmouseout=function()
{
float.style.display="none";
bigContainer.style.display="none";
}
// 鼠标移动事件
cover.onmousemove=function(e)
{
// 确定鼠标能到达的边界
var left=e.clientX-(cover.offsetLeft+float.offsetWidth/2);
var right=(cover.offsetLeft+cover.offsetWidth-float.offsetWidth/2)-e.clientX;
var top=e.clientY-(cover.offsetTop+float.offsetHeight/2);
var bottom=(cover.offsetTop+cover.offsetHeight-float.offsetHeight/2)-e.clientY;
if(left>0&&right>0){
float.style.left=e.clientX-float.offsetWidth/2+'px';
}
if(top>0&&bottom>0){
float.style.top=e.clientY-float.offsetHeight/2+'px';
}
var persentX=left/(cover.offsetWidth-float.offsetWidth);
var persentY=top/(cover.offsetHeight-float.offsetHeight);
// 显示放大部分
image[0].style.left=-persentX*(image[0].offsetWidth-bigContainer.offsetWidth)+'px';
image[0].style.top=-persentY*(image[0].offsetHeight-bigContainer.offsetHeight)+'px';
}
}
重点变量注释:
[object.offsetWidth],[object.offsetHeight],[object.offsetTop],
[object.offsetLeft]:获取元素自身的宽 高 top left的值
[e.clientX],[e.clientY]:鼠标事件的鼠标坐标
大致思路:
1通过鼠标事件控制放大镜和漂浮层的出现与消失
2在cover上移动时,漂浮层跟随
3放大镜内的图片与漂浮层区域内的图片动作同步