放大镜
随着网上购物的逐渐火热,放大镜在许多的购物平台,广泛的应用。如下图,是京东商城的放大镜,它对用户查看商品的细节,作用很大
下面让我们来看下如何用面向对象的的方法,来编写它。
OOA
在面向对象的程序编写中:最重要的就是面向对象过程的分析,
- 元素选择
- 事件驱动
- 元素隐藏
- 小图移动 大图跟随
OOD
面对对象设计:首先建一个构造函数,并且实例化,人后根据OOA 编写原型对象
OOD
function Magnifier(){
}
Magnifier.prototype = {
constructor : Magnifier,
//初始化
init : function(){
},
//事件绑定
bindEvent:function(){
},
//元素隐藏
eleToggle:function(){
},
//小图移动 大图跟随
eleMove:function(){
},
}
OOP
面向对象编程:在前两步完成之后,我们就可以进行编程了,不过在编程中我们也会发现,在前期分析的不足,实时改正就好
下面是我所实现的效果图
下面是我的简单布局:便于你解读后续代码
<div class="small">
<img src="images/small.jpg" alt="">
<span class="grayBox"></span>
</div>
<div class="big">
<img src="images/big.jpg" alt="">
</div>
<div class="xsmall">
<img src="images/xsmall.jpg" alt="">
</div>
<div class="xsmall2">
<img src="images/xsmall2.jpg" alt="">
</div>
CSS样式代码
*{
margin: 0;
padding: 0;
}
.small {
width: 350px;
height: 350px;
position: relative;
margin-left: 200px;
margin-top: 100px;
border:4px solid #ddd;
box-shadow: 0 0 5px rgba(0,0,0,.5);
}
.small img{
width: 100%;
height: 100%;
}
.small .wrap{
width: 100%;
height: 100%;
position: absolute;
z-index: 999;
}
.small .grayBox{
display: none;
width: 100px;
height: 100px;
/* background-image: url(../images/timg.jpg); */
background-size:400px 400px;
background-position: 0 0;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
position: absolute;
left: 0;
top: 0;
}
.big{
width: 500px;
height: 500px;
position: absolute;
left: 700px;
top: 100px;
border:1px solid #f10;
display: none;
overflow: hidden;
}
.big img{
position: absolute;
}
.xsmall {
width: 50px;
height: 50px;
position: absolute;
left :200px;
top:462px;
border:2px solid #ddd;
}
.xsmall2 {
width: 50px;
height: 50px;
position: absolute;
left :255px;
top:462px;
border:2px solid #ddd;
}
下面是js的详细代码,便于读者进行查看
// OOP :
function Magnifier(options){
this.init(options)
}
Magnifier.prototype = {
constructor : Magnifier,
//初始化
init : function(options){
for(var attr in options){
this[attr+"_ele"] = this.$(options[attr])
}
//只获得一次,节省性能
this.small_box_offset = {
left:this.small_box_ele.offsetLeft,
top :this.small_box_ele.offsetTop,
//offsetWidth:取值时带有padding和border的宽度 去px
width:parseInt(getComputedStyle(this.small_box_ele).width),
height:parseInt(getComputedStyle(this.small_box_ele).height),
}
// console.log(this.small_box_offset)
//因为初始为display:none,offset的测量为0,要用getComputedStyle;
this.cutting_box_offset = {
width:parseInt( getComputedStyle(this.cutting_box_ele)