具有相似结构的Div将仅在单击一个时起作用

问题描述 投票:0回答:2

我使用div来显示标题和段落。我在右下角添加了一个拇指向上的图像。我的意图是,当点击拇指时,它会改变颜色和比例。但是,使用我的代码,当点击一个拇指时,所有拇指都会以相同的方式行事。

我正在使用Django模板,这是一个模型。我认为我的js文件有问题,请让我知道如何修复它。非常感谢。

var $icon = $(".icon");
$icon.on('click', function() {
  if ($icon.closest("div").hasClass('anim')) {
    $icon.closest("div").removeClass('anim');
  } else {
    $icon.closest("div").addClass('anim');
  }
});
.icon-wrapper {
  position: absolute;
  bottom: 0;
  right: 0;
  padding: 10px;
  text-align: center;
  cursor: pointer;
  display: inline-block;
}

.icon-wrapper .icon {
  color: #90A4AE;
}

.icon-wrapper i {
  transform: scale(1);
}

.icon-wrapper.anim .icon {
  color: #39CCCC;
}

.icon-wrapper.anim i {
  animation: icon-animation cubic-bezier(0.165, 0.84, 0.44, 1) 1.2s;
}

@keyframes icon-animation {
  0% {
    transform: scale(0);
  }
  100% {
    transform: scale(1);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="things">
  <div class="thing">
    <div class="icon-wrapper">
      <span class="icon"><i class="fa fa-thumbs-up"></i></span>
    </div>
    <h2>Wachet auf, ruft uns die Stimme</h2>
    <p>Wachet auf, ruft uns die Stimme (Awake, calls the voice to us),[1] BWV 140,[a] also known as Sleepers Wake, is a church cantata by Johann Sebastian Bach, regarded as one of his most mature and popular sacred cantatas. He composed the chorale cantata
      in Leipzig for the 27th Sunday after Trinity and first performed it on 25 November 1731.</p>
    <small>Jan. 2, 2018, 6:38 a.m.</small>
  </div>

  <div class="thing">
    <div class="icon-wrapper">
      <span class="icon"><i class="fa fa-thumbs-up"></i></span>
    </div>
    <h2>Wachet auf, ruft uns die Stimme</h2>
    <p>Wachet auf, ruft uns die Stimme (Awake, calls the voice to us),[1] BWV 140,[a] also known as Sleepers Wake, is a church cantata by Johann Sebastian Bach, regarded as one of his most mature and popular sacred cantatas. He composed the chorale cantata
      in Leipzig for the 27th Sunday after Trinity and first performed it on 25 November 1731.</p>
    <small>Jan. 2, 2018, 6:38 a.m.</small>
  </div>
</div>

enter image description here

javascript jquery css django
2个回答
0
投票

这是因为你将类添加到最接近的$icon,这个选择器覆盖页面的所有.icon。以这种方式重构您的代码:

var $icon = $(".icon");
 $icon.on('click', function() {
 if ($(this).closest("div").hasClass('anim')) {
   $(this).closest("div").removeClass('anim');
 } else {
   $(this).closest("div").addClass('anim');
 }
});

1
投票

我会这样做:

var $icon = $(".icon");
$icon.on('click', function() {
  var $closest = $(this).closest('div'); // you need to use $(this) for currently clicked icon

  $closest.toggleClass('anim'); // just use toggleClass instead of an if (unless you have other functionality in the if)
});
© www.soinside.com 2019 - 2024. All rights reserved.