简体   繁体   English

多个DIV的JavaScript悬停事件

[英]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. 我试图让文本出现在JS的mouseover事件上,但我发现一个可以正常工作的JS可以满足我的要求,但它似乎只能在其中一个DIV上工作,而不是所有DIV上都能工作。

Here is the HTML: 这是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: 这是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. 我有多个DIV,我希望它可以处理,但是我对JS不太了解,因此我尝试了一些修补,但个人没有修复。 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. 因此,我只是想找到一种方法来基本上使所有“ lImg”的DIV都具有相同的鼠标悬停事件,而不必制作多个JS文件。

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. HTML元素应具有唯一的标识符。 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). 标识符lImg对于每个div标签应该是唯一的(并且lImg也不具有很好的描述性,因此最好使用更好的命名约定)。

Once you have the class on both div tags, you can then use the class .imageHover and bind to the on the click event. 在两个div标签上都具有该类之后,就可以使用.imageHover类并绑定到click事件。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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