惯例先上效果
放大镜效果图忽略我手残晃动(太强会被撞到地上),(也不知道为什么明明浏览器背景是白色,录出来的图就是蓝色,求推荐好用的截动图软件,么么哒~)
分析:
看似图片是被放大了的效果,实则是一张大图实现移动,下图是三张不同大小的图,左图最小放在图片展示列表里,中间是正常图片,右侧图片最大用于展示放大镜效果。
废话不多说,直接上代码!
HTML布局
图中标识为所用id<div id='box' class="box">
<div id="small">
![](images/pic01.jpg)
<span id="mark"></span>
</div>
<div id="big">
![](images/pic1.jpg)
</div>
<div id="pic">
<span><</span>
![](images/pic001.jpg)
![](images/pic002.jpg)
![](images/pic003.jpg)
![](images/pic004.jpg)
![](images/pic005.jpg)
<span>></span>
</div>
</div>
CSS样式
*{ margin: 0; padding: 0;}
.box{
width: 352px;
height: 414px;
margin: 30px;
position: relative;
}
#small{
width:350px;
height: 350px;
border: 1px solid #cccccc;
margin-bottom: 20px;
position: relative;
}
#small span{
width: 200px;
height: 200px;
background-color: rgba(253,241,104,0.6);
position: absolute;
top:0; left:0;
cursor: move;
display: none;
}
#small img{
width:100%;
}
#big{
width: 450px;
height: 450px;
position: absolute;
top: 0; left: 355px;
border: 1px solid #ccc;
overflow: hidden;
display: none;
}
#bigPic{
position: absolute;
top:0; left:0;
}
#pic{
font-size: 25px;
line-height:50px;
}
#pic img{
width: 50px;
vertical-align: middle;
cursor: pointer;
box-sizing: border-box;
}
js
window.onload = function(){
var smallBox = $('small');
var smallPic = smallBox.children[0];
var bigBox = $('big');
var imgs = $('pic').getElementsByTagName('img');
var mark = $('mark');
var bigPic = $('bigPic');
smallBox.onmouseover = function(even){
mark.style.display = 'block';
bigBox.style.display = 'block';
smallBox.onmousemove= function(event){
var event = event||window.event;
var disLeft = event.clientX - $('box').offsetLeft - mark.offsetWidth * 0.5;
var disTop = event.clientY - $('box').offsetTop - mark.offsetHeight * 0.5;
//判断左右是否出界
if(disLeft<0){
disLeft=0;
}else if(disLeft>smallBox.offsetWidth - mark.offsetWidth-2){
disLeft = smallBox.offsetWidth - mark.offsetWidth-2;
}
//判断上下是否出界
if(disTop<0){
disTop=0;
}else if(disTop>smallBox.offsetHeight - mark.offsetHeight-2){
disTop=smallBox.offsetHeight - mark.offsetHeight-2;
}
mark.style.left = disLeft + 'px';
mark.style.top = disTop + 'px';
//大盒子图片走起来
//大图移动距离 / mark移动的距离 = 大图的宽度 / 小图的宽度(纵向距离同理)
bigPic.style.left = -disLeft/smallBox.offsetWidth*bigPic.offsetWidth+'px';
bigPic.style.top = -disTop/smallBox.offsetHeight*bigPic.offsetHeight+'px';
};
//鼠标离开盒子大盒子和mark消失
smallBox.onmouseout = function(){
mark.style.display = 'none';
bigBox.style.display = 'none';
}
};
//替换图片
for(var i=0;i<imgs.length;i++){
var oli = imgs[i];
oli.index = i+1;
oli.onmouseover = function(){
smallPic.src = 'images/pic0'+this.index+'.jpg';
bigPic.src = 'images/pic'+this.index+'.jpg';
for(var i=0;i<imgs.length;i++){
imgs[i].style.border = 'none';
}
this.style.border = '2px solid red';
}
}
};
/**
* 获取标签
* @param tagId 标签Id
*/
function $(tagId){ return document.getElementById(tagId); }
我的反思:
作为一个green hand,直接分析一个动画是怎么做的确实有点难度(拿我自己举例),所以先把布局做出来,然后再一步一步分析,进行动画分解,最后优化代码。
网友评论