简体   繁体   中英

Trying to create a menu with jQuery but my code isn't working

I am trying to create a menu with jQuery as in when the user mouseover an element the menu would show up and would hide when user moves the mouse away.

My html code:

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

but this doesn't seem to work.

Bind the mouseleave event out of img mouseover, because binding event within mouseover, bind the mouseleave event to like-box each time, which is not good and unnecessary.

$('.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

NOTE:

  • $('.img') should be $('img') because you image has no class called img , . selector is use for access class. read about selectors and also class-selector

Your problem is here:

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

$(this) is img , the parent() is div.span8.img , and the siblings() are...none.

Try with:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM