为什么jQuery的show()和hide()方法会触发淡入淡出?

Gra*_*wan 3 html javascript jquery

我正试图在客户端显示和隐藏推文,但jQuery正在折叠元素hide()并将其淡入其中show().

相关HTML:

<aside>
  <div class="tweet-author">
    <p class="name">Graham Swan</p>
    <p class="position">Managing Partner</p>
  </div>

  <div class="tweet">
    <blockquote>Just had the greatest cup of coffee ever!</blockquote>
    <div class="clearfix">
      <time>2 minutes ago <span>via</span> Twitter</time>
      <a href="#">Hide Tweets</a>
    </div>
  </div>
</aside>
Run Code Online (Sandbox Code Playgroud)

相关的JavaScript:

// Hide tweets when "Hide Tweets" link is clicked
$(document).on('click', 'div.tweet > div.clearfix > a', function(e) {
  e.preventDefault();
  $("div.tweet").hide(function() {
    $("div.tweet-author > p.name").html("Show Recent Tweets");
    $("div.tweet-author > p.position").html("By the iNovia Team");
    $("aside").addClass("click-to-show-tweets");
  });
});

// Show tweets when "Show Recent Tweets" link is clicked
$(document).on('click', 'aside.click-to-show-tweets', function(e) {
  e.preventDefault();
  $("div.tweet").show(function() {
    $("div.tweet-author > p.name").html("Graham Swan");
    $("div.tweet-author > p.position").html("Managing Partner");
    $("aside").removeClass("click-to-show-tweets");
  });
});
Run Code Online (Sandbox Code Playgroud)

jQuery正在执行以下操作:

  • div.tweethide()调用元素时折叠元素而不是立即隐藏它.
  • 淡入(在webkit浏览器中)或扩展(在moz浏览器中)div.tweet元素,而不是在show()调用时立即显示它.

我已经尝试了jQuery的v1.7.2和v.1.8.2,以及不同的浏览器,但都产生了相同的效果.

有谁知道为什么会这样?

如果有帮助,您可以在http://grahamswan.com/clients/inovia上看到一个实例.

Asa*_*din 7

您正在使用的方法签名(.hide( duration [, callback] ))用于动画隐藏.立即隐藏的签名只是$("div.tweet").hide();为了立即隐藏元素,您可以0在回调参数之前传递持续时间的参数.

更好的是,只需在调用后立即调用该功能$("div.tweet").hide();.你真的不需要回调; 隐藏动作是同步的.

$("div.tweet").hide();
(function() {
    $("div.tweet-author > p.name").html("Show Recent Tweets");
    $("div.tweet-author > p.position").html("By the iNovia Team");
    $("aside").addClass("click-to-show-tweets");
  })();
Run Code Online (Sandbox Code Playgroud)