<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>放大镜</title>
<style>
* {
margin: 0;
padding: 0;
}
#left {
width: 200px;
height: 200px;
position: relative;
display: inline-block;
}
#left img {
width: 200px;
height: 200px;
display: block;
}
.mark {
width: 40px;
height: 40px;
background: rgb(230, 82, 82);
position: absolute;
left: 0;
top: 0;
}
#content {
width: 200px;
height: 200px;
display: inline-block;
overflow: hidden;
position: relative;
}
#content img {
width: 800px;
height: 600px;
display: block;
position: absolute;
left: 0;
top: 0;
}
</style>
</head>
<body>
<div id="left">
<img src="https://img2.baidu.com/it/u=2102736929,2417598652&fm=26&fmt=auto&gp=0.jpg" alt="">
<div class="mark"></div>
</div>
<div id="content">
<img src="https://img2.baidu.com/it/u=2102736929,2417598652&fm=26&fmt=auto&gp=0.jpg" alt="">
</div>
</body>
</html>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(function(paams) {
$('#left div.mark').on('mousedown', function(e) {
var eve = e || window.event;
// 鼠标按下获取当前鼠标距离盒子的距离
var disX = eve.pageX - $(this).position().left;
var disY = eve.pageY - $(this).position().top;
$(document).on('mousemove', function(e) {
var eve = e || window.event;
var l = eve.pageX - disX;
var t = eve.pageY - disY;
// 限定范围
if (l < 0) {
l = 0;
}
if (l > $('#left').width() - $('.mark').width()) {
l = $('#left').width() - $('.mark').width();
}
if (t < 0) {
t = 0;
}
if (t > $('#left').height() - $('.mark').height()) {
t = $('#left').height() - $('.mark').height();
}
// 设定值
$('.mark').css({
left: l,
top: t
});
// 大图的显示,大图的显示距离按照比例计算
var scaleX = l / ($('#left').width() - $('.mark').width()); // 大图应该走的左边的距离百分比=Mark盒子的left值/(左边盒子的宽-Mark盒子的宽);
var left = scaleX * ($('#content img').width() - $('#content').width()); // 实际大图应该走的左边距=百分比*(大图的宽-右边盒子的宽);
var scaleY = t / ($('#left').height() - $('.mark').height());
var top = scaleY * ($('#content img').height() - $('#content').height());
$('#content img').css({
left: -left,
top: -top
});
});
$(document).on('mouseup', function() {
$(this).off('mousemove');
$(this).off('mouseup');
});
return false;
});
});
</script>
2021-08-13 js-商品图片放大镜?
最新推荐文章于 2024-04-07 10:09:13 发布