简体   繁体   中英

JavaScript Hover event for multiple DIV

I'm trying to have text appear on mouseover event with JS and I found a working JS that will do what I want but it only seems to work on one of the DIVs and not all of them.

Here is the HTML:

<TABLE><TR>
    <TD><A href="#"><DIV id="lImg">
       <IMG width=210px height=160px src="/img.png">
       <DIV id="lTxt">TXT1<BR>TXT2</DIV>
    </DIV></A></TD>
    <TD><A href="#"><DIV id="lImg">
       <IMG width=210px height=160px src="/img.png">
       <DIV id="lTxt">TXT1<BR>TXT2</DIV>
    </DIV></A></TD>
</TR></TABLE>

and this is the JS:

$(window).load(function(){
$('#lImg').hover(
    function(){
        $(this).find('div').stop(true, true).animate({
            'bottom': '+=60'
        }, 300);
    },
    function(){
        $(this).find('div').stop(true, true).animate({
            'bottom': '-=60'
        }, 250);
    }
);
});

I have Multiple DIVs that I want this to work on but I don't know too much about JS and I tried tinkering with it a little and got no fix personally. So I'm just trying to find a way to basically have all my DIVs that are "lImg" to have the same mouseover event work without having to make multiple JS files.

My Apologies if this was asked before, I must have missed it or searched for the wrong keywords.

If this can also be done in a simpler way I'm up for that too.

HTML elements should have unique identifers. You can use a class instead for this scenario.

For example:

<DIV id="lImg" class="imageHover">

The identifier lImg should be unique to each div tag (And lImg isn't very descriptive either so a better naming convention may be preferred).

Once you have the class on both div tags, you can then use the class .imageHover and bind to the on the click event.

$('.imageHover').hover(
    function(){
        $(this).find('div').stop(true, true).animate({
            'bottom': '+=60'
        }, 300);
    },
    function(){
        $(this).find('div').stop(true, true).animate({
            'bottom': '-=60'
        }, 250);
    }
);

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