jQuery悬停显示多个元素

jQuery on hover show for multiple elements

本文关键字:元素 显示 悬停 jQuery      更新时间:2023-09-26

我有一个页面,其中包含多行,每行都封装在<div id="result">中;

<div id="result"><a href="http://www.domain.com/">Link Name</a><iframe src="http://www.domain.com/" style="width:285px;height:285px;border:0px;margin:0px" scrolling="no"></iframe></div>

我目前正在使用以下jQuery在悬停时显示<a>标签;

$(document).ready(function(){
    $('#result iframe').hover(function(){
        $('#result a').fadeIn(200);
    },function(){
        $('#result a').fadeOut(200);
    });
});

然而,悬停仅适用于第一个<div id="result">,并且还显示每个<div id="result"><a>标签,而不仅仅是用户悬停的标签

我该怎么解决这个问题?

您可以尝试将results更改为类

$(document).ready(function(){
    $('.result').hover(function(){ // <-- change to class.. and bind to wrapper div
        $(this).find('a').fadeIn(200);
    },function(){
        $(this).find('a').fadeOut(200);
    });
});

假设我理解你奇怪的东西:

Html

    <div class="result">
        <a href="http://www.domain.com/" style="display:none;">Link Name</a>
        <iframe src="http://www.domain.com/" style="width:285px;height:285px;border:0px;margin:0px;background:red;" scrolling="no"></iframe>
    </div>
    <div class="result">
        <a href="http://www.domain.com/" style="display:none;">Link Name</a>
        <iframe src="http://www.domain.com/" style="width:285px;height:285px;border:0px;margin:0px;background:red;" scrolling="no"></iframe>
    </div>

jQuery

$('.result iframe').hover(function(e) {
   $(this).parent().find('a').fadeIn(); 
}, function() {
     $(this).parent().find('a').fadeOut();   
});

参见小提琴

悬停编辑。

Nb:e.preventDefault();点击事件,如果您不希望通过点击提交链接。

这样试试:

$(document).ready(function(){
$('#result iframe').hover(function(){
    $('#result a').fadeIn(200);
    $('#result a').fadeOut(200);
});
});

如果您想只捕获<a>标记,而不是针对每个,而是针对特定的<div id="result">,您可以尝试在jQuery代码中指定,例如:

$(document).ready(function(){
    $('#result:nth-child(1) iframe').hover(function(){
        $('#result:nth-child(1) a').fadeIn(200);
    },function(){
         $('#result:nth-child(1) a').fadeOut(200);
    });
});

因此,这将只针对id="result"的第一个div。通过更改第n个child(0)-第n个child(1)-第n-child(2)来抓住其他人。。。

另一种解决方案:您还可以为每个<a>标记设置一个id,也可以使用一个类来捕获所需的特定元素。