慣例先上效果
忽略我手殘晃動(太強會被撞到地上)柏蘑,(也不知道為什么明明瀏覽器背景是白色磁椒,錄出來的圖就是藍色走越,求推薦好用的截動圖軟件,么么噠~)
分析:
看似圖片是被放大了的效果贩耐,實則是一張大圖實現(xiàn)移動弧腥,下圖是三張不同大小的圖,左圖最小放在圖片展示列表里憔杨,中間是正常圖片骨杂,右側圖片最大用于展示放大鏡效果尿赚。
廢話不多說漫蛔,直接上代碼低淡!
HTML布局
<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,直接分析一個動畫是怎么做的確實有點難度(拿我自己舉例)寻狂,所以先把布局做出來岁经,然后再一步一步分析,進行動畫分解蛇券,最后優(yōu)化代碼缀壤。