之前有在网上见过原生js实现放大镜的效果,但是代码量略多,今天和大家分享下我自己用jq实现的放大镜效果吧!
首先html布局结构和样式 贴上代码给大伙看一下:
html结构:
<div class="pic">
<img src="images/xiaotu.jpg" >
<div class="big-pic"></div>
</div>
css样式:
.pic{position:relative;
float:left;
width:350px;
height:350px;
border:1px solid #ccc;
margin-left:100px;
margin-top:100px;
}
.big-pic{
position:absolute;
width:170px;
height:170px;
background:#FEDE4F;
opacity: .8;
display: none;
cursor:move;
}
.datu{
float:left;
width:400px;
height:400px;
margin-top:100px;
background: url(images/datu.jpg) no-repeat;
display: none;
}
jq代码:
$(function(){
$(‘.pic‘).mouseenter(function(){
$(‘.big-pic‘).show();
$(‘.datu‘).show();
})
$(‘.pic‘).mouseleave(function(){
$(‘.big-pic‘).hide();
$(‘.datu‘).hide();
})
$(‘.pic‘).mousemove(function(e){
var x = e.pageX - $(‘.pic‘).offset().left - 172/2;
var y = e.pageY - $(‘.pic‘).offset().top - 172/2;
// 限制鼠标的x,y轴活动范围
if(x < 0){
x = 0;
}else if(x > 180){
x = 180;
}
if(y < 0){
y = 0;
}else if(y > 180){
y = 180;
}
$(‘.big-pic‘).css({
‘left‘ : x,
‘top‘ : y
});
var datux = -x * 800 / 460;
var datuy = -y * 800 / 460;
$(".datu").css("background-position",datux + "px " + datuy + "px");
})
$(function(){
$(‘.pic‘).mouseenter(function(){
$(‘.big-pic‘).show();
$(‘.datu‘).show();
})
$(‘.pic‘).mouseleave(function(){
$(‘.big-pic‘).hide();
$(‘.datu‘).hide();
})
$(‘.pic‘).mousemove(function(e){
var x = e.pageX - $(‘.pic‘).offset().left - 170/2;
var y = e.pageY - $(‘.pic‘).offset().top - 170/2;
// 限制鼠标的x,y轴活动范围
if(x < 0){
x = 0;
}else if(x > 230){
x = 230;
}
if(y < 0){
y = 0;
}else if(y > 230){
y = 230;
}
$(‘.big-pic‘).css({
‘left‘ : x,
‘top‘ : y
});
console.log(x , y);
var datux = -x * 800 / 350;
var datuy = -y * 800 / 350;
$(".datu").css("background-position",datux + "px " + datuy + "px");
})
})
效果图如下:
原文:http://www.cnblogs.com/sherryyao/p/7384573.html