jquer 放大镜绑定事件
时间: 2023-07-29 22:07:26 浏览: 50
你可以使用jQuery的`mouseenter()`和`mouseleave()`事件来绑定放大镜功能。
例如,假设你的HTML结构如下:
```html
<div class="product-image">
<img src="product.jpg" alt="Product Image">
<div class="zoom"></div>
</div>
```
你可以使用以下jQuery代码来实现放大镜功能:
```javascript
$(document).ready(function() {
// 定义放大区域的宽度和高度
var zoomWidth = 200;
var zoomHeight = 200;
// 绑定鼠标进入事件
$('.product-image').mouseenter(function() {
// 获取原始图片的宽度和高度
var imgWidth = $(this).find('img').width();
var imgHeight = $(this).find('img').height();
// 计算放大镜块的尺寸和位置
var zoomLeft = Math.floor(imgWidth / 2 - zoomWidth / 2);
var zoomTop = Math.floor(imgHeight / 2 - zoomHeight / 2);
var zoomCss = {
'width': zoomWidth + 'px',
'height': zoomHeight + 'px',
'left': zoomLeft + 'px',
'top': zoomTop + 'px'
};
// 创建并添加放大镜块
var zoomBlock = $('<div>').addClass('zoom-block').css(zoomCss);
$(this).append(zoomBlock);
// 绑定鼠标移动事件
$(this).mousemove(function(e) {
// 计算鼠标在原始图片中的位置
var imgX = e.pageX - $(this).offset().left;
var imgY = e.pageY - $(this).offset().top;
// 计算放大镜块的位置
var zoomX = Math.floor(imgX / imgWidth * zoomWidth);
var zoomY = Math.floor(imgY / imgHeight * zoomHeight);
var zoomBlockCss = {
'background-image': 'url(' + $(this).find('img').attr('src') + ')',
'background-position': '-' + zoomX + 'px -' + zoomY + 'px'
};
// 更新放大镜块的位置和背景图
zoomBlock.css(zoomBlockCss);
});
});
// 绑定鼠标离开事件
$('.product-image').mouseleave(function() {
$(this).find('.zoom-block').remove();
$(this).off('mousemove');
});
});
```
这段代码会在鼠标进入`.product-image`元素时创建并显示放大镜块,并在鼠标移动时更新放大镜块的位置和背景图。当鼠标离开`.product-image`元素时,放大镜块会被删除。