【问题标题】:jQuery mouseenter/leave doesn't work with li:nth-child():beforejQuery mouseenter/leave 不适用于 li:nth-child():before
【发布时间】:2018-10-07 02:47:54
【问题描述】:

在下面的代码中,我尝试使用 jquery 显示内容:text

如果我删除 :before 它会起作用!为什么 jQuery 不允许这样做,而 javascript 会这样做。

This post (7 years ago) 谈论我的问题,但它解决了问题而没有给出简单的解决方案。

今天没有针对:before的简单解决方案?

感谢您的帮助

$(document).ready(function() {
  $("div").mouseenter(function() {
    $("li:nth-child(2):before").show();
  });
  $("div").mouseleave(function() {
    $("li:nth-child(2):before").hide();
  });
});
li {
  display: none;
}

li:before {
  content: 'Show me';
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul>
  <li>This is a paragraph.</li>
  <li>This is a second paragraph.</li>
</ul>

<div style="width:30px; height:30px; background:black;cursor:pointer;position:absolute; top:50px;"></div>

【问题讨论】:

    标签: jquery css-selectors pseudo-element


    【解决方案1】:

    伪元素的可见性取决于其主要元素li:nth-child(2) 的可见性(即display 状态)。所以你必须在你的 jQuery 函数中添加相应的行来显示/隐藏主要元素:

    $(document).ready(function(){
        $("div").mouseenter(function(){
            $("li:nth-child(2)").show();
            $("li:nth-child(2):before").show();
        });
        $("div").mouseleave(function(){
            $("li:nth-child(2)").hide();
            $("li:nth-child(2):before").hide();
        });
    });
    li{display:none;}
    li:before{content:'Show me';}
    <!DOCTYPE html>
    <html>
    <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    </head>
    <body>
    <ul>
    <li>This is a paragraph.</li>
    <li>This is a second paragraph.</li>
    </ul>
    
    <div style="width:30px; height:30px; background:black;cursor:pointer;position:absolute; top:50px;"></div>
    
    
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 2022-01-20
      • 2012-06-01
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多