【问题标题】:is there a way i can dry this code or use a better approach for this toggle effect有没有办法我可以干掉这段代码或使用更好的方法来实现这种切换效果
【发布时间】:2020-02-27 21:00:27
【问题描述】:

我想制作一个切换效果,当您单击一个图标时,它会显示一些文本并且该图标会切换。当您单击新显示的文本时,文本会切换并返回图标。

`<div class="we-do">
          <img class="icon" src="images/design_icon.png">
          <h5>DESIGN</h5>
          <div class="hide">
           <p class="clickable"> Our design practice offers a full range of services 
            including brand strategy,interaction and
            visual design and user experience testing</p>
          </div>
        </div>
        <div class="we-do">
          <img class="icon" src="images/dev_icon.png">
          <h5>DEVELOPMENT</h5>
          <div class="hide">
            <p class="clickable1">All engineers are fluent in the latest enterprise, mobile 
            and web development technologies.</p>
          </div>
        </div>
        <div class="we-do">
          <img class="icon" src="images/product_icon.png">
          <h5>PRODUCT MANAGEMENT</h5>
          <div class="hide">
            <p class="clickable2">Planning and development is iterative.
             requirements evolve.</p>
          </div>
        </div>enter code here
  $(".clickable").click(function() {
    $("#hide").slideToggle("slow");
    $("#icon").slideToggle("slow");
  })
  $(".clickable1").click(function() {
    $("#hide1").slideToggle("slow");
    $("#icon1").slideToggle("slow");
  })
  $(".clickable2").click(function() {
   $("#hide2").slideToggle("slow");
   $("#icon2").slideToggle("slow");
  })```

【问题讨论】:

    标签: jquery toggle slidetoggle


    【解决方案1】:

    您的 html 具有由 we-do 类的外部 div 定义的上下文。

    <div class="we-do">
      <img class="icon" src="images/design_icon.png">
      <h5>DESIGN</h5>
      <div class="hide">
        <p class="clickable">
          Our design practice offers a full range of services 
          including brand strategy,interaction and
          visual design and user experience testing
        </p>
      </div>
    </div>
    

    鉴于此,您不需要不同的课程。你只需要正确使用contextual lookups

    $('.clickable').on('click', function(e){
      // find the contextual parent to the elements
      var $weDo = $(e.target).closest('.we-do');
    
      // find the related elements
      var $hide = $weDo.find('.hide');
      var $icon = $weDo.find('.icon');
    
      // do your work
      $hide.slideToggle("slow");
      $icon.slideToggle("slow");
    });
    

    【讨论】:

    • 非常感谢,我在想几乎类似的东西。
    • 代码不起作用,因为可点击已隐藏。我希望它首先显示图标和标题,然后单击图标时,描述显示并且图标变为隐藏。当您单击描述时,应该会发生相反的情况。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    • 2014-06-12
    • 2020-03-11
    • 1970-01-01
    • 2020-08-22
    • 2012-01-11
    相关资源
    最近更新 更多