为什么我在使用多个切换时遇到问题?

时间:2012-09-17 22:17:50

标签: jquery toggle fade slide

在我的网站上,如果单击某个按钮,则会切换fadeToggle,并同时执行slideToggle。如果单击其他按钮,则完全相同,但内容不同。但如果你同时按下它们,它们最终会失去同步。一个是切换,另一个不是。

按下信息和那些客户,它会让人感到困惑。它们变得不同步。

有没有办法避免这种重叠?

这是jquery:

   <script type="text/javascript">
  $(document).ready(
    function(){

        $('#stop').click(function (e) { 
    e.preventDefault(); });

         $('#information').click(function() {
   $("#projectwrap").slideToggle('slow'); 
   $("#us").fadeToggle('slow');
   });

      $('#clients').click(function() {
   $("#projectwrap").slideToggle('slow'); 
   $("ul").fadeToggle('slow');
   });


});
</script>

如果你感到困惑,我也是!

1 个答案:

答案 0 :(得分:0)

jsBin demo

逻辑问题是您在#projectwrap#information点击时切换#clients!毫无意义的是,您无法再点击#title元素来查看主要内容。这是一个糟糕的 UX (用户体验)。

您应该使用此HTML结构: 为您的所有可点击元素添加一个类.toggler,并在内部元素.content上切换状态!

<div id="stop"> 

  <div id="clients">
    <h2 class="toggler">clients</h2>
    <div class="content" style="display:none;">
      <ul>
        <li>list</li>
        <li>list</li>
        <li>list</li>
        <li>list</li>
      </ul>  
    </div>
  </div>

  <div id="projectwrap">
    <h1 class="toggler">projectwrap</h1>
    <div class="content">
      <p>text here.........</p>
    </div>
  </div>

  <div id="information">
    <h2 class="toggler">info</h2>
    <div class="content" style="display:none;">
       about us..........
     </div>
  </div>

</div>

现在我们将使用jQuery搜索可点击的.next('.content')元素!

jQuery的:

$('#stop').click(function (e) { 
     e.preventDefault();
});

$('.toggler').click(function() {
  var $nextContent = $(this).next('.content');
  var nextContIsHidden = $nextContent.is(':hidden');
  if(nextContIsHidden){
    $('.content:visible').slideUp('slow'); // hide all visible
    $nextContent.slideDown('slow');    
  }else{                          // if we're clicking the title of the visible one
    $nextContent.slideUp('slow'); // if is already visible hide it
    $('#projectwrap .content').slideDown('slow'); // and slide the main content
  }
});