【问题标题】:jQuery click don't work in li:nth-child()jQuery 点击在 li:nth-child() 中不起作用
【发布时间】:2022-01-20 05:23:02
【问题描述】:

我想为其他li:nth-child 制作动画,但它不起作用。所以首先我有

<li><a href="#"> H </a></li>
<li><a href="#"> A </a></li>
<li><a href="#"> B </a></li>
<li><a href="#"> C </a></li>

所以第一个孩子将移动第二个孩子。这是jquery,但我不知道这是否正确。

$('li:nth-child(1) a').click(function() {
   $('li:nth-child(2) a').animate({
      left: '100px',
   });
});

这是我的DEMO

【问题讨论】:

  • 您的 li:nth-child 代码工作正常 - 只有 left: 位不起作用,如添加另一个动画所示,例如 "font-size": '10px',
  • 那我应该用什么换'left'来移动它呢?
  • 添加li &gt; a { position:relative; } css(可能还有其他/更好的方法,但这在您的小提琴中有效)编辑使用relative 相对于li。更新小提琴:jsfiddle.net/zrf0nsp8
  • 你有什么来源为什么它需要绝对位置吗?我在这方面很糟糕哈哈..无论如何谢谢。

标签: html jquery css


【解决方案1】:

使用:nth-of-type 而不是:nth-childnth-child(2) 表示您想要访问li 的第二个子元素null,因为您只有一个元素)

animate 中的 left 属性不会执行任何操作,除非 a 子级具有绝对位置。

css

a {
  position: absolute;
}

js

$('li:nth-of-type(1) a').click(function(e) {
    $('li:nth-of-type(2) a').animate({
        left: '100px',
    });
});

【讨论】:

  • OP 没有问题:nth-child,它工作正常。不是li :nth-child(2)(没有空格来表示li 的孩子)。问题中的示例需要 ul 包装器。
  • @freedomn-m 是的,你是对的
猜你喜欢
  • 2018-10-07
  • 2012-06-01
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-22
  • 1970-01-01
相关资源
最近更新 更多