如何修改代码实现非选中父元素的Swatch移出时保留title值
解决方案:保留Swatch的Title显示逻辑
我来帮你搞定这个问题~核心点就是调整mouseleave事件里的判断逻辑,别再在父元素无selected类时清空title了,不管鼠标移开时父元素有没有选中状态,都保持显示当前Swatch自己的title属性值就行。
原生JavaScript实现示例
// 遍历所有Swatch元素 document.querySelectorAll('.swatch').forEach(swatch => { // 提前缓存当前Swatch的title值,避免重复DOM查询 const swatchTitle = swatch.getAttribute('title'); // 假设用来显示title的元素是Swatch内部的.swatch-title-display const titleDisplay = swatch.querySelector('.swatch-title-display'); // 鼠标进入时设置显示title(可选,也可以初始化就显示) swatch.addEventListener('mouseenter', () => { titleDisplay.textContent = swatchTitle; }); // 修改后的mouseleave事件逻辑 swatch.addEventListener('mouseleave', () => { // 关键:不管父元素有没有selected类,都设置为当前Swatch的title titleDisplay.textContent = swatchTitle; // 保留你原来的逻辑:如果父元素有selected类则返回false const parent = swatch.parentElement; if (parent.classList.contains('selected')) { return false; } }); });
jQuery实现示例(如果项目用jQuery的话)
$('.swatch').each(function() { const $this = $(this); const swatchTitle = $this.attr('title'); const $titleDisplay = $this.find('.swatch-title-display'); $this.on('mouseenter', function() { $titleDisplay.text(swatchTitle); }); $this.on('mouseleave', function() { // 核心修改:移除清空操作,直接赋值当前Swatch的title $titleDisplay.text(swatchTitle); // 保留原有逻辑:父元素有selected类则返回false const $parent = $this.parent(); if ($parent.hasClass('selected')) { return false; } }); });
逻辑说明
原来的问题出在mouseleave事件里,当父元素没有selected类时你执行了清空title的操作。现在只需要把那部分清空的代码替换成设置为当前Swatch的title值,就能实现:无论鼠标是否移出,只要触发mouseleave,都保持显示该Swatch自身的title属性内容。
内容的提问来源于stack exchange,提问作者Jgunzblazin
相关产品推荐
相关产品推荐

