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

Chrome中动态添加按钮功能失效求助(Firefox正常)

解决Chrome中鼠标悬停最后一个div不显示按钮的问题

咱先来捋清楚问题根源:Chrome和Firefox对DOM选择器的解析有细微差异,尤其是:last-child这个选择器——Chrome会把父元素里的空白文本节点(比如代码里的换行、空格)也算作子元素,导致你认为的“最后一个.item-block-row”,在Chrome眼里可能不是真正的:last-child,这就直接导致后续的按钮添加逻辑没触发。

给你几个靠谱的修复思路,亲测有效:

1. 替换:last-child为更可靠的索引判断

用元素的索引和同级别元素总数对比,完全规避浏览器对空白节点的判定差异:

$(document).on('mouseenter', '.item-block-row', function(){
    const $currentItem = $(this);
    // 检查是否在目标容器内
    if($currentItem.closest('#glaceblock').length || $currentItem.closest('#sorbetblock').length){
        // 精准删除当前容器内的按钮,避免误删其他区域的元素
        $currentItem.closest('#glaceblock, #sorbetblock').find('.deleteSorbGlaceItem').remove();
        
        // 获取当前容器内所有同级别元素
        const $siblingItems = $currentItem.parent().find('.item-block-row');
        // 判断是否是最后一个元素(索引从0开始,所以总数减1)
        if($currentItem.index() === $siblingItems.length - 1){
            const maximumCount = 10;
            if($('.layout-item-row').length >= maximumCount){
                // 仅显示删除按钮的逻辑
                $currentItem.append('<button class="deleteSorbGlaceItem">删除</button>');
            } else {
                // 显示+按钮和删除按钮的逻辑
                $currentItem.append('<button class="addItem">+</button><button class="deleteSorbGlaceItem">删除</button>');
            }
        }
    }
});

2. 改用mouseenter事件代替mouseover

mouseover会在鼠标进入子元素时反复触发,容易导致按钮被频繁删除和添加,Chrome对这种高频事件的处理会更严格,换成mouseenter后,只有鼠标首次进入元素时才触发逻辑,更稳定。

3. 精准控制按钮的删除范围

原来的$('.deleteSorbGlaceItem').remove()是全局删除所有该类按钮,改成只删除当前容器内的按钮,避免影响其他区域的元素,也减少不必要的DOM操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:29:20