仿天猫商城图片放大镜效果

Original 2019-03-19 17:03:03 217
abstract:index.html: <!DOCTYPE html> <html lang="en"> <head> <title>仿天猫商品详情放大镜效果</title> <link rel="stylesheet" href="static/css/st
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>仿天猫商品详情放大镜效果</title>
<link rel="stylesheet" href="static/css/style.css">
<script src="static/js/jquery.js"></script>
</head>
<body>
<div id="normal">
<img src="static/images/5.jpg" alt="">
<div id="show"></div>
</div>
<div id="big">
<img src="static/images/5.jpg" alt="">
</div>

<script>
$(function(){
$('#big').hide();
// 鼠标移上图片
$('#normal').mouseover(function(){
$('#show').show()
$('#big').show();
$(this).mousemove(function(yd){
// 小方块跟随鼠标移动而移动
$('#show').css(
{
'left':yd.pageX-$('#show').width()/2,
'top':yd.pageY-$('#show').height()/2
}
)
})

//绑定鼠标在normal内部移动
$('#normal').mousemove(function(e){
//获取鼠标当前的位置
var x = e.clientx;
var y = e.clienty;

//获取原图窗口距离文档的偏移位置 
var dx = $('#normal').offset().left;
var dy = $('#normal').offset().top;

//计算鼠标的相对位置
var sx = x - dx;
var sy = y - dy;

//获取小框的宽高
var mw = $('#show').width()/2;
var mh = $('#show').height()/2;

//给入鼠标移动,小框移动的距离
$('#show').css(
{
left:sx-mw+'px',
top:sy-mh+'px'
}
)

//控制小框只能在原图窗口的范围内移动
//获取小框的偏移位置
var lw = $('#show').position().left;
var lh = $('#show').position().top;
//获取x,y轴移动的最大的距离
var maxW = $('#normal').width() - $('#show').width();
var maxH = $('#normal').height() - $('#show').height();

//左边界
if(lw <= 0){
$('#show').css('left','0px')
}
//右边界
if(lw >= maxW){
$('#show').css('left',maxW+'px')
}

//上边界
if(lh <= 0){
$('#show').css('top','0px')
}
//下边界
if(lh >= maxH){
$('#show').css('top',maxH+'px')
}
//重新获取一下小框的偏移位置
var lw = $('#show').position().left;
var lh = $('#show').position().top;

var newX = lw*3;
var newY = lh*3;
$('#big').find('img').css({
'left':-newX+'px',
'top':-newY+'px'
})
})
})

// 鼠标移出图片
$('#normal').mouseleave(function(){
$('#show').hide()
$('#big').hide();
})
})

</script>
</body>
</html>

style.css:
*{
margin: 0px;
padding: 0px
}

/* 展示图 */
#normal{
width: 450px;
height: 450px;
border: 1px solid #000;
position: fixed;
top:20px;
left: 20px;
}
#normal img{
width: 100%;
height: 100%;
}

/* 放大镜区域长宽 */
#show{
width: 150px;
height: 150px;
background: #754930;
opacity: 0.4;
position: absolute;
display: none;
}

/* 右边放大镜长宽 */
#big{
width: 450px;
height: 450px;
border: 1px solid #000;
position: relative;
left: 520px;
top: 20px;
overflow: hidden;
}

/* 放大镜内部图片的长宽 */
#big>img{
position: absolute;
width: 1350px;
height: 1350px;
}

/* 放大镜内部图片的长宽/展示图 = 放大镜长宽/放大镜区域长宽 */
/* 宽度、长度 一定要等比 */

clientX、clientY:

鼠标相对于浏览器窗口可视区域的X,Y坐标(窗口坐标),可视区域不包括工具栏和滚动条。

pageX、pageY:

类似于event.clientX、event.clientY,但它们使用的是文档坐标而非窗口坐标,包括滚动条。

offset()设置或者返回匹配到的元素相对于文档的偏移。

Correcting teacher:灭绝师太Correction time:2019-03-20 09:24:40
Teacher's summary:完成很好,思路清晰,看的出来是很认真完成的!

Release Notes

Popular Entries