You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce单品页面:鼠标悬停商品图片时替换商品标题

解决WooCommerce单品页面悬停商品图片替换标题的问题

方法一:CSS相邻兄弟选择器方案

这种方案适合静态替换场景,需要给标题添加一个备用元素,通过CSS控制显示隐藏:

  1. 修改单品页面模板
    找到主题的single-product.php(或标题对应的模板片段,比如single-product/title.php),在原标题后添加备用标题元素:
<h1 class="product_title entry-title">原商品标题</h1>
<span class="hover-title">悬停时显示的标题</span>
  1. 添加CSS样式
    在主题自定义CSS或style.css中添加:
/* 默认隐藏备用标题 */
.hover-title {
  display: none;
  /* 继承原标题样式,避免排版错乱 */
  font-size: inherit;
  font-weight: inherit;
}

/* 悬停图片容器时切换标题显示状态 */
.woocommerce-product-gallery:hover + .product_title {
  display: none;
}
.woocommerce-product-gallery:hover + .product_title + .hover-title {
  display: block;
}

注意:如果图片容器和标题不是直接相邻的兄弟元素,需要调整选择器层级,比如用.product-container:hover .product_title,具体根据你的页面HTML结构修改。


方法二:JavaScript动态替换方案

这种方案更灵活,无需额外添加元素,还能在鼠标离开时恢复原标题:

原生JS版本

document.addEventListener('DOMContentLoaded', function() {
  const imageGallery = document.querySelector('.woocommerce-product-gallery');
  const productTitle = document.querySelector('.product_title');
  
  if (!imageGallery || !productTitle) return;
  
  const originalText = productTitle.textContent;
  const hoverText = '替换后的标题内容'; // 按需自定义

  imageGallery.addEventListener('mouseover', () => {
    productTitle.textContent = hoverText;
  });

  imageGallery.addEventListener('mouseout', () => {
    productTitle.textContent = originalText;
  });
});

jQuery版本(WooCommerce默认加载jQuery)

jQuery(document).ready(function($) {
  const $gallery = $('.woocommerce-product-gallery');
  const $title = $('.product_title');
  
  if (!$gallery.length || !$title.length) return;
  
  const originalText = $title.text();
  const hoverText = '替换后的标题内容';

  $gallery.hover(
    () => $title.text(hoverText),
    () => $title.text(originalText)
  );
});

进阶优化:如果需要给不同商品设置不同的悬停标题,可以利用WooCommerce自定义字段,从后台添加hover_title字段,然后在JS中通过data-属性读取该值替换。


注意事项

  • 修改主题模板时建议使用子主题,避免主题更新导致修改丢失;
  • 调试时可用浏览器开发者工具查看元素类名,确保选择器匹配正确;
  • CSS方案仅支持静态文本替换,动态需求优先用JS方案。

内容的提问来源于stack exchange,提问作者tecne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 19:52:20