Woocommerce single-product页用jQuery实现背景图放大功能失效如何解决
Woocommerce single-product页面自定义放大镜效果失效解决方案
核心失效原因
- WordPress内置jQuery默认开启
noConflict模式,直接使用$符号调用jQuery会报错,代码无法正常执行 - 本地测试用的是挂载了背景图的
.wp-post-image类div元素,但Woocommerce默认商品详情页的.wp-post-image是真实<img>标签,给<img>设置background相关属性不会生效 - 代码执行时机过早,在Woocommerce商品图库组件初始化完成前就执行,无法绑定到对应DOM元素
- Woocommerce默认自带商品图片悬停放大功能,会和自定义代码产生冲突
修正方案
1. 先禁用Woocommerce默认放大镜功能
在当前使用主题的functions.php文件末尾添加以下代码:
add_filter( 'woocommerce_single_product_zoom_enabled', '__return_false' );
2. 修正后的CSS代码
添加到主题「自定义-额外CSS」配置项中:
/* 适配Woocommerce商品图容器结构 */ .woocommerce-product-gallery .woocommerce-product-gallery__image { background-size: 100%; background-repeat: no-repeat; position: relative; overflow: hidden; } /* 隐藏原生img标签,保留占位 */ .woocommerce-product-gallery .woocommerce-product-gallery__image img { opacity: 0; display: block; width: 100%; height: auto; }
3. 修正后的JS代码
添加到主题footer.php文件</body>标签之前,或者用自定义代码插件插入到页脚位置:
jQuery(document).on('woocommerce_gallery_init_complete', function() { // 遍历所有商品图容器,预加载背景图 jQuery('.woocommerce-product-gallery__image').each(function() { let imgUrl = jQuery(this).find('img').attr('src'); jQuery(this).css('background-image', 'url(' + imgUrl + ')'); }); // 绑定鼠标移动事件 jQuery('.woocommerce-product-gallery__image').mousemove(function(e) { let rect = this.getBoundingClientRect(); let x = e.clientX - rect.left; let y = e.clientY - rect.top; let moveX = (x * -100 / rect.width) + 50; let moveY = (y * -100 / rect.height) + 50; jQuery(this).css({ 'background-size': '200%', 'background-position': moveX + '% ' + moveY + '%' }); }); // 鼠标移出后恢复默认样式 jQuery('.woocommerce-product-gallery__image').mouseleave(function() { jQuery(this).css({ 'background-size': '100%', 'background-position': 'center' }); }); });
内容的提问来源于stack exchange,提问作者Ferhat
相关产品推荐
相关产品推荐

