【问题标题】:Make an image in an li disappear with hover using jQuery使用jQuery悬停使li中的图像消失
【发布时间】:2015-08-18 10:56:51
【问题描述】:

尝试在li 中创建img,以便在鼠标悬停在元素上时隐藏并在鼠标离开元素时显示。 稍后我想让一个段落显示 li 类的名称来代替图像,但我现在想专注于图像隐藏。

我已经搞砸了一段时间,即使在查看与此相关的其他帖子后,我似乎也无法找出问题所在。

<ul id="language">
    <li class="a"><img src="img/a.png" alt="a"></li>
    <li class="b"><img src="img/b.png" alt="b"></li>
</ul>
<script src="//code.jquery.com/jquery-1.11.3.min.js" type="text/javascript" charset="utf-8"></script>
<script src="nameDisplay.js" type = "text/javascript" charset="utf-8"></script>

在 nameDisplay.js 中

$('#language li').hover(function(){
    $(this 'img').hide();
}, function(){
    $(this 'img').show();
});

【问题讨论】:

    标签: javascript jquery html css jquery-hover


    【解决方案1】:

    只用css,不用jQuery

    #language li:hover img{
        display: none;
    }
    

    【讨论】:

    • 当鼠标悬停在使用css的img时,我可以添加一个

      吗?因为那是我要采取的下一步

    • 你想在p元素中显示什么
    • @asdkhalifa 是的,你可以 :) 将

      插入

    • 并使用 "display: none" 然后在 li:hover p 上使用 "display:block"
  • 好的!当我使用您建议的代码时:悬停,元素会闪烁而不是消失,直到鼠标离开元素
  • 【解决方案2】:

    $(function() {
      $('#language li').hover(function() {
        $('img', this).hide();
        // You can either of these 
        // $(this).find('img') 
        // $(this).children('img') 
      }, function() {
        $('img', this).show();
      });
    });
    <script src="//code.jquery.com/jquery-1.11.3.min.js" type="text/javascript" charset="utf-8"></script>
    <ul id="language">
      <li class="a">
        <img src="img/a.png" alt="a">
      </li>
      <li class="b">
        <img src="img/b.png" alt="b">
      </li>
    </ul>

    您查找图像的选择器不正确。您可以使用上下文选择器或.find()children() 方法

    $(function() {
        $('#language li').hover(function(){
            $('img', this).hide();
            // You can either of these 
            // $(this).find('img') 
            // $(this).children('img') 
        }, function(){
            $('img', this).show();
        });
    });
    

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签