最近学了JQuery的一些简单知识,跟着教学做了个放大镜功能的网页。内容是将鼠标放在一张图片上,对应位置放大后显示出来。
原理是用两张成比例的图片,小图片上对应的某块区域,显示出来的放大区域实际上是大图片上的位置(小图片上对应的某块区域的位置大小乘以两张图片的倍数)??
or(当小图片上对应区域移动时,显示放大的区域的背景图片的位置反向移动)
下面是代码:
首先定义网页的布局:#fangdajing下有#left 和 #right
#left下有img 、#float 、#mask
#left :放小图片、要放大的区域float 、一个图片区域mask
#right:放大的区域
<div id="fangdajing">
<div id="left">
<img src="imgs/small.jpg" >
<div id="float"></div>
<div id="mask"></div>
</div>
<div id="right"></div>
</div>
设置元素的style:
#fangdajing #left{//设置大小为小图片的大小
width: 300px;
height: 168px;
float:left;
position: relative;//位置为绝对,以便等下要放大的区域只在#left里面
}
#fangdajing #left #img{
width: 300px;
height: 168px;
}
#fangdajing #left #mask{
width: 100%;
height: 100%;
position: absolute;
left: 0;
top: 0;
background-color: black;
opacity: 0;
}
#fangdajing #left #float{
width: 50px;
height: 50px;
background-color: #FFFF00;
opacity: 0.5;
position: absolute;
left: 0;
top: 0;
display: none;
}
#fangdajing #right{//大小为#float * 两张图片大小的倍数
width: 200px;
height: 200px;
background-image: url(imgs/big.jpg);
float:left;
margin-left: 80px;
display: none;
}
设置完样式后,接下来就是实现放大效果:
我们在立即执行函数(function($){}(jQuery)里面实现,形参传$,实参传jQuery 这样解决接下来写Jquery插件命名冲突的问题。在立即执行函数里面编写插件fangdajing()方法
(function($){
$.fn.extend({
fangdajing:function(){
this.each(function(){//遍历所有调用fangdajing()的jQuery对象
var that = this;//记录当前调用fangdajing()的jQuery对象
//把$('#left')限定在当前调用fangdajing()的jQuery对象(选取当前jQuery对象下的#left标签)
$('#left',this).mousemove(function(evt){//调用鼠标移动方法
var float = $('#float',this);//把float 限定在$('#left')
var x = evt.offsetX;//取鼠标在left里面的x坐标
var y = evt.offsetY;//取鼠标在left里面的y坐标
x = x - float.width()/2;//进行此计算是为了下面把float的中心x坐标设置为鼠标的x坐标
y = y - float.height()/2;//与上同理
//限定float在left里面
if(x<0){
x=0;
}
if(y<0){
y=0;
}
//此时的$(this)就是 $('#left',this)
if(x > $(this).width() - float.width()){
x = $(this).width() - float.width();
}
if(y > $(this).height() - float.height()){
y = $(this).height() - float.height();
}
//设置鼠标指针在float的中心
float.css({
left:x,
top:y
})
//设置right
$('#right',that).css({
//float与right的大小倍数为4,然后 * -1 将right的背景图位置与float在left中的位置相对应
//也就是当left向右移动n px,right的背景图就向左移动n*4 px
backgroundPosition: x * -4 +'px ' + y * -4 + 'px'
})
}).mouseover(function(){//鼠标移到小图片上时, 显示小方块和 放大的区域
$('#left #float,#right',that).show();
}).mouseout(function(){//鼠标移出小图片时, 隐藏小方块和 放大的区域
$('#left #float,#right',that).hide();
});
})
}
})
})(jQuery)
表述得很烂,但大概就是如此啦,如有错误,请大佬指正。