如何在悬停按钮时通过文本切换图像,并延迟反向切换

How to toggle an image by text, on hover of a button, and delay the reverse toggle

本文关键字:图像 延迟 文本 悬停 按钮      更新时间:2023-09-26

我有下面的html,其中有一个由图像表示的互动程序,它下面有一个小的"whatsthis"图标。当人悬停在图标上时,我想显示一些文本来代替图像,当人悬停时隐藏它。

<div id="tileImage" class="tile1 tileDiv"></div>
<div id="tileText" class="tileDiv" style="display:none">
    <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas ac eros vitae nulla tincidunt volutpat. Etiam tortor ante, consequat in laoreet id, bibendum eget libero. Suspendisse vel arcu purus, id laoreet massa. </span>
</div>
<div id="tileContent">
    <span>Something</span>
    <div id="whatsthis"></div>
</div>

我已经编写了以下javascript

$(document).ready(function(){
    $("#whatsthis").hover(function(){
        $(this).parent().parent().find("#tileImage").hide();
        $(this).parent().parent().find("#tileText").show();
    },function(){
        $(this).parent().parent().find("#tileText").delay(1000).hide();
        $(this).parent().parent().find("#tileImage").show();
    });
});

它运行良好,但有两件事

  1. 我不希望文本在悬停时立即消失,那么如何添加延迟
  2. 如果光标从"whatthis"图标移动到描述文本,那么我不希望发生切换效果

我该怎么做?

阅读JQuery文档:

只有队列中的后续事件才会延迟例如,这不会延迟不使用效果队列的.show()或.hide()的无参数形式

我创建了一个小解决方案。。。不是最好的,但看看吧。

        $(document).ready(function(){
            var hideShow = function( el ){
                var titleImageEl;
                var titleTextEl;
                function init(){ ativateListener(); }
                function ativateListener(){
                    $(el).mouseenter(function(){
                        titleImageEl = $(this).parent().parent().find("#tileImage");
                        titleTextEl = $(this).parent().parent().find("#tileText");
                        titleImageEl.hide();
                        titleTextEl.show();
                    });
                    $(el).mouseleave({root: this}, delay);
                }
                function deactivateListener(){
                    $(el).unbind('mouseenter');
                    $(el).unbind('mouseleave');
                }
                function exit(){
                    titleImageEl.show();
                    titleTextEl.hide();
                    ativateListener();
                }
                function delay(){
                    deactivateListener();
                    setTimeout(exit, 1000);
                }
                return {
                    init: init
                }
            };
            $('body #whatsthis').each(function(i) {
                new hideShow($(this)).init();   
            });
        });

使用onmouseover和onmouseout可能会更好,但这里是修复的jQuery

$(document).ready(function(){
    $("#whatsthis").hover(function(){
        $("#tileImage").hide();
        $("#tileText").show();
    },function(){
        setTimeout( function() {
            $("#tileText").hide();
            $("#tileImage").show();
        }, 1000 );
    });
});