javascript - 具有相似结构的div仅在单击一个时都会起作用

标签 javascript jquery css django

我使用 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

最佳答案

我会这样做:

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

关于javascript - 具有相似结构的div仅在单击一个时都会起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48062163/

相关文章:

javascript - 导出带有参数的多个函数

javascript - 如何在同一个文本框中显示不同的功能?

css - 将 div 放置在另一个 div 之上后不需要的空间

css - fieldset firefox 溢出 CSS 修复

javascript - 如何在指令中将元素推送到数组 - AngularJS

javascript - 对象未定义但 console.log 显示一个对象

jquery - ToBootstrap 与容器宽度对齐

php - 使用 DIV 回显结果

javascript - 升级到 jQuery UI 1.10 时如何更改 `cache` 和 `ajaxOptions`?

html - 如何在div中的段落样式下创建段落类