我需要在悬停时使用选择器,在悬停外使用变量集来找到特定的链接

I need to use a selector on hover and a variable set outside hover to find a specific link

本文关键字:悬停 链接 选择器 变量      更新时间:2023-11-27

这对我来说很难解释,所以我会尽我所能。这里有这个代码:

$('#navibar a').hover(function(){
    var position = $(this).position(); 
    var width = $(this).width();
    $('#underliner').css({'width': '' + width + '','left': position.left});
    //$('#underliner').show("slide", { direction: "left" }, 100);
    $('#underliner').stop().animate({opacity: 1}, 30).show();
}, function () {
    var homePos = $(this).find(attr(activePageHref)).position();
    var homeWidth = $(this).find(attr(activePageHref)).width();
    //$('#underliner').css({'width': '' + homeWidth + '','left': homePos.left});
    //$('#underliner').show("slide", { direction: "left" }, 100);
    //$('#underliner').stop().animate({opacity: 1}, 30).show();
    alert(activePageHref);
});

activePageHref在此之外设置为已单击的页面。在警报中,它显示正确(例如,假设它的值是"home"。我需要以某种方式将#underline.css的位置和宽度设置为悬停时选择的导航中的页面链接,那么有没有办法"找到"其他的"a"并使用它们?希望在代码中我想做的很明显。这是我的标记:

<ul id="navibar">
            <li><a href="home">Home</a></li>
            <li><a href="products">Products</a></li>
            <li><a href="games">Games</a></li>
            <li><a href="store">Store</a></li>
            <li><a href="support">Support</a></li>
            <li><a href="community">Community</a></li>
        </ul>

此外,我知道第一块代码是"大时代"错误的,这只是我决定在这里发帖之前出于愤怒和绝望所做的最后一件事。

使用属性选择器查找href为activePageHref 的链接

$('#navibar a').hover(function(){
    var position = $(this).position(); 
    var width = $(this).width();
    $('#underliner').css({'width': '' + width + '','left': position.left});
    //$('#underliner').show("slide", { direction: "left" }, 100);
    $('#underliner').stop().animate({opacity: 1}, 30).show();
}, function () {
    var homePos = $(this).parents('#navibar').find('a[href="'+activePageHref+'"]').position();
    var homeWidth = $(this).parents('#navibar').find('a[href="'+activePageHref+'"]').width();
    //$('#underliner').css({'width': '' + homeWidth + '','left': homePos.left});
    //$('#underliner').show("slide", { direction: "left" }, 100);
    //$('#underliner').stop().animate({opacity: 1}, 30).show();
    alert(activePageHref);
});

首先,您可以通过类似event.target的东西来选择"a"
第二,将activeClass添加到目标
第三,通过选择器获取其他a,例如$("ul#navibar li a:not(.activeClass)")在这里,您将获得数组中那些未激活的a,您可以通过$.each 进行遍历

愿它能帮你一点忙。