有什么方法可以使这段代码变干,或者可以使用更好的方法来实现这种切换效果

时间:2019-11-01 14:55:24

标签: jquery toggle slidetoggle

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

`<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");
  })```

1 个答案:

答案 0 :(得分:0)

您的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");
});
相关问题