簡體   English   中英

jQuery / CSS-將鼠標懸停在具有相同href的元素上更改CSS類

[英]jQuery/CSS - Change css class on hover on elements with same href

我有兩個單獨的UL作為菜單。 當我將鼠標懸停在第一個菜單項上時,我希望第二個菜單項更改文本顏色。 也許是一種解決方案,其中與您所懸停的鏈接具有相同href的鏈接會更改CSS類? 我該如何使用jQuery?

<ul class="firstMenu jQueryHover">
 <li><a href="href1">bla</a></li>
 <li><a href="href2">bla2</a></li>
</ul>

<ul class="secondMenu">
 <li><a href="href1">blabla (same href as firstMenu item you hovered changes this elements css class)</a></li>
 <li><a href="href2">blabla (same href as firstMenu item you hovered changes this elements css class)</a></li>
</ul>

如果要影響具有相同href所有鏈接,包括懸停在上方的鏈接:

$("a").hover(function() {
    $("a[href='" + $(this).attr("href") + "']").addClass("yourClass"); 
}, function() {
    $("a[href='" + $(this).attr("href") + "']").removeClass("yourClass");
});

這利用屬性名稱選擇器來查找與當前懸停的鏈接具有相同href所有鏈接。

這是一個有效的例子

如果您希望這樣做,則僅其他鏈接會更改(而不是已鏈接的鏈接),那么您可以使用jQuery not方法排除已鏈接的元素。 從您的問題尚不清楚,您是否要更改具有相同href所有鏈接,還是要更改所有其他鏈接而不是當前懸停的鏈接。

$("a").hover(function() {
    $("a[href='" + $(this).attr("href") + "']").not(this).addClass("yourClass");
}, function() {
    $("a[href='" + $(this).attr("href") + "']").not(this).removeClass("yourClass");
});

更改所有具有相同href的錨標記

$("a").hover(function() {
    $("a[href='" + $(this).attr("href") + "']").addClass("hover-class-name"); 
}, function() {
    $("a[href='" + $(this).attr("href") + "']").removeClass("hover-class-name");
});

但是,我看不到您為什么要在頁面上擁有兩個具有相同href的鏈接? 您是否考慮過使用類名而不是href來鏈接錨點?

應該很簡單:

$(".jQueryHover a").hover(function(){
   if($(this).hasClass("hovering"))
      {
         $(this).removeClass("hovering");
         $('a[href="'+$(this).attr('href')+'"]').removeClass("hovering");
      }
   else {
      $(this).addClass("hovering");
      $('a[href="'+$(this).attr('href')+'"]').addClass("hovering");
   }
});

您可以這樣做:

$('.firstMenu ').hover(function(){
    var href = $(this).attr('href');
    $('.secondMenu  a[href='+href+']').addClass('newClass');
},
function(){
    var href = $(this).attr('href');
    $('.secondMenu  a[href='+href+']').removeClass('newClass');
}
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM