效果
所需图片
pic为同一张图
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>jq图片放大镜</title>
<style type="text/css">
* {
padding: 0;
margin: 0;
}
.magnify {
width: 550px;
margin: 80px auto;
position: relative;
}
.large {
width: 180px;
height: 180px;
position: absolute;
border-radius: 100%;
/*使用多重阴影,来实现玻璃的效果 */
box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.8), 0 0 7px 7px rgba(0, 0, 0, 0.3), inset 0 0 40px 2px rgba(0, 0, 0, 0.3);
cursor: crosshair;
display: none;
overflow: hidden;
}
.large_pic {
position: absolute;
top: 0;
left: 0;
display: block;
}
.large_pic img {
display: block;
width: 1595px;
height: auto;
}
.small {
display: block;
width: 550px;
}
</style>
</head>
<body>
<div class='magnify'>
<div class='large'>
<div class="large_pic">
<img src='pic.jpg'>
</div>
</div>
<img src='pic.jpg' class='small'>
</div>
<script type="text/javascript" src='jquery-1.7.2.min.js'></script>
<script type="text/javascript">
$(document).ready(function () {
var native_width;
var native_height;
$('.large_pic img').load(function () {
//获取图片本身宽高
var img_obj = new Image();
img_obj.src = $(this).attr('src');
//适应不同的图片的大小
var ratio = 1595 / img_obj.width;
native_width = img_obj.width * ratio;
native_height = img_obj.height * ratio;
$('.magnify').mousemove(function (e) {
// 获得鼠标X轴和Y轴的坐标
// 先获得magnify相对与document的定位position
var magnify_offset = $(this).offset();
// 用鼠标相对与文档的位置减去鼠标相对于magnify这个人容器的位置,得到鼠标的位置
var mouse_x = e.pageX - magnify_offset.left;
var mouse_y = e.pageY - magnify_offset.top;
//放大镜的隐藏与显示、
if (mouse_x > 0 && mouse_y > 0 && mouse_x < $(this).width() && mouse_y < $(this).height()) {
$('.large').fadeIn(100);
} else {
$('.large').fadeOut(100);
}
if ($('.large').is(':visible')) {
// 放大镜图片背景的定位是根据鼠标在小图片上改变的位置来改变的、
// 先得到放大的比例,定位这个放大镜里背景图片的定位
//var ratio_x = mouse_x/$('.small').width();//得到的是缩放的比例
//var large_x = ratio_x*native_width;
// 鼠标位置在放大镜的中间位置显示、
//large_x = large_x - $('.large').width()/2;
// 因为背景图片的定位、这里需要转化为负值、
//large_x = large_x*-1;
// 整合步骤
var rx = Math.round(mouse_x / $('.small').width() * native_width - $('.large').width() / 2) * -1;
var ry = Math.round(mouse_y / $('.small').height() * native_height - $('.large').height() / 2) * -1;
// 放大镜跟随鼠标的效果
// 放大镜移动的位置 相对于文档的位置 减去 放大镜相对于放大这个层的offset的位置、
// 再减去放大镜宽高的一半、保证放大镜的中心跟随鼠标
var gx = mouse_x - $('.large').width() / 2;
var gy = mouse_y - $('.large').height() / 2;
$('.large').css({
'left': gx,
'top': gy
});
$('.large_pic').css({
'left': rx,
'top': ry
})
}
})
})
})
</script>
</body>
</html>
1706

被折叠的 条评论
为什么被折叠?



