【问题标题】:Trying to create a menu with jQuery but my code isn't working尝试使用 jQuery 创建菜单,但我的代码不起作用
【发布时间】:2023-04-08 18:04:01
【问题描述】:

我正在尝试使用 jQuery 创建一个菜单,就像当用户将鼠标悬停在一个元素上时,菜单会显示,而当用户将鼠标移开时会隐藏。

我的html代码:

<div class="span8 img">
   <img src="http://farm4.staticflickr.com/3198/2978120072_ca00381e08.jpg" alt="" width="550px" height="368px">
   <div class="like-box">Like</div> 
</div>

CSS:

.like-box {
    display: block;
    background: rgba(255, 255, 255, .9);
    padding: 15px;
    position: absolute;
    left: -1px;
    width: 94%;
    bottom: -1px;
    display: none;
}

Javascript:

$('.img').mouseover(function() {
        $(this).parent().siblings('.like-box').css('display', 'block');
        $(this).parent().siblings('.like-box').mouseleave(function() {
        $(this).css('display', 'none');
        })
    });

但这似乎不起作用。

【问题讨论】:

    标签: javascript jquery jquery-selectors jquery-events


    【解决方案1】:

    mouseleave事件绑定到img mouseover之外,因为在mouseover内绑定事件,所以每次都将mouseleave事件绑定到like-box,这样不好也没有必要。

    $('.like-box').mouseleave(function() {
        $(this).css('display', 'none');
    })
    $('img').mouseover(function() {
        $(this)  // this point to img
          .next('.like-box')  // point to like-box
          .css('display', 'block');       
    });
    

    DEMO

    注意:

    • $('.img') 应该是 $('img') 因为您的图像没有名为 img 的类,. 选择器用于访问类。阅读selectorsclass-selector

    【讨论】:

      【解决方案2】:

      你的问题在这里:

      $(this).parent().siblings('.like-box')
      

      $(this)imgparent()div.span8.imgsiblings() 是……没有。

      尝试:

      $(this).next('.like-box')
      

      【讨论】:

      • 好的,我的选择器名称错误。但它不会隐藏在鼠标悬停上。但我有代码 $(this).next('.like-box').mouseleave(function() { $(this).css('display', 'none'); });
      猜你喜欢
      • 2015-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      • 2021-09-21
      相关资源
      最近更新 更多