jQuery 图片局部放大效果是一种常见的网页交互设计,它允许用户在鼠标悬停在图片的某个区域时,该区域会放大显示,从而提供更详细的视觉信息。这种效果通常用于产品展示、艺术作品展示等场景。
以下是一个使用 jQuery 实现图片局部放大效果的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery 图片局部放大效果</title>
<style>
.image-container {
position: relative;
display: inline-block;
}
.image-container img {
width: 300px;
height: 200px;
}
.magnify-lens {
position: absolute;
display: none;
width: 100px;
height: 100px;
background-repeat: no-repeat;
cursor: crosshair;
border: 1px solid #000;
}
</style>
</head>
<body>
<div class="image-container">
<img src="path/to/your/image.jpg" alt="Sample Image">
<div class="magnify-lens"></div>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
var $image = $('.image-container img');
var $magnifyLens = $('.magnify-lens');
var magnifyFactor = 2;
$image.on('mousemove', function(e) {
var $this = $(this);
var offset = $this.offset();
var x = e.pageX - offset.left;
var y = e.pageY - offset.top;
var lensX = x - $magnifyLens.width() / 2;
var lensY = y - $magnifyLens.height() / 2;
if (lensX < 0) lensX = 0;
if (lensY < 0) lensY = 0;
if (lensX > $this.width() - $magnifyLens.width()) lensX = $this.width() - $magnifyLens.width();
if (lensY > $this.height() - $magnifyLens.height()) lensY = $this.height() - $magnifyLens.height();
$magnifyLens.css({
left: lensX,
top: lensY
});
$magnifyLens.css('background-image', 'url(' + $this.attr('src') + ')');
$magnifyLens.css('background-position', '-' + (lensX * magnifyFactor) + 'px -' + (lensY * magnifyFactor) + 'px');
});
$image.on('mouseleave', function() {
$magnifyLens.hide();
});
$image.on('mouseenter', function() {
$magnifyLens.show();
});
});
</script>
</body>
</html>
mousemove
事件中的位置计算逻辑,确保放大区域的左上角坐标在图片范围内。magnifyFactor
的值,增加放大倍数。background-image
和 background-position
的值正确。通过以上方法,可以实现一个基本的 jQuery 图片局部放大效果,并解决常见的实现问题。
领取专属 10元无门槛券
手把手带您无忧上云