【问题标题】:Hover over any paragraph, append div with little message, hover off, it fades out, is this right?将鼠标悬停在任何段落上,添加带有少量消息的 div,悬停,它会淡出,对吗?
【发布时间】:2011-02-18 10:43:28
【问题描述】:

http://jsfiddle.net/nicktheandroid/3AraQ/

当 P 悬停在上面时,#both 会附加到该段落并居中。当我将鼠标悬停在一个新段落上时,它会在第一个 P 上淡出并在现在悬停的 P 上淡入。这是最好的方法吗?稍后我将使用它来允许人们单击书签图像,然后当他们悬停 P 时,它将执行我下面的代码所做的事情,然后当他们单击该 P 时,它将为该段落创建一个书签,但我真的只需要以下代码的帮助。谢谢!

$('p').hover(function() {

    $(this).append('<span id="both">BOOKMARK THIS</span>')
        $('#both').animate({opacity: 1.0}) 

}, function(){
        $('#both').fadeOut(600, function(){
            $(this).remove()
        })
});

它运行不顺利,它只是不对......

【问题讨论】:

    标签: javascript jquery hover fadein fadeout


    【解决方案1】:

    只使用class而不是id:

    $('p').hover(function() {
    
        $(this).append('<span class="both">BOOKMARK THIS</span>')
            $('.both').animate({opacity: 1.0}) 
    
    }, function(){
            $('.both').fadeOut(600, function(){
                $(this).remove()
            })
    });
    

    http://jsfiddle.net/yzXxH/

    【讨论】:

      【解决方案2】:

      我可能会稍微改变一下:

      $('p').hover(function() {
      
          $('<span class="both">BOOKMARK THIS</span>')
              .appendTo(this)
              .animate({opacity: 1.0}) 
      
      }, function(){
      
          var both = $(this).find('span.both');
          both.fadeOut(600, function(){
              both.remove()
          });
      
      });
      

      我使用 class 而不是 id 的原因是,当您离开一个段落并输入下一个段落时,您将暂时拥有其中两个 spans —— 一个逐渐消失的旧段落和添加到新段落的段落。拥有两个具有相同id 的元素是无效的并且充满危险。

      如果我回到同一段,我可能也会提前取消动画:

      $('p').hover(function() {
      
          $(this).find('span.both').stop().remove(); // Stop and remove it if it's there
          $('<span class="both">BOOKMARK THIS</span>')
              .appendTo(this)
              .animate({opacity: 1.0}) 
      
      }, function(){
      
          var both = $(this).find('span.both');
          both.fadeOut(600, function(){
              both.remove()
          });
      
      });
      

      【讨论】:

        【解决方案3】:

        在我看来,您不需要继续添加和删除 dom。只需将跨度默认设置为style="display:none;",然后

        $('p').hover(function() {
                $(this).find('#both').animate({opacity: 1.0}) 
        
        }, function(){
                $(this).find('#both').fadeOut(600)
        });
        

        这并不完全有效,您可能必须在默认样式中弄乱不透明度才能获得所需的内容。不过,无需操纵 dom。

        【讨论】:

        • 问题是 HTML 中的重复跨度,有时会被语音浏览器、搜索引擎机器人等读取。如果你有几个 P,我不是在谈论大小问题。每次添加 span 比将它添加到源代码中要少。
        • @Capsule 确保在某些情况下您想要操纵 dom,例如您给出的原因。但从 OP 的问题和示例代码来看,我不认为这是其中之一,我认为始终使用问题允许的最简单解决方案是一种很好的做法。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-01-25
        相关资源
        最近更新 更多