簡體   English   中英

jQuery懸停每個不同的背景顏色

[英]jQuery hover each different background color

如何hover每種不同的background-color 這些代碼設置background-color起作用:

var dlcabgColors = [
    'rgb(233, 147, 26)', 'rgb(22, 145, 190)', 'rgb(22, 107, 162)' , 'rgb(27, 54, 71)'
];

var i = 0;
$('.abc').each(function() {
    $(this).css('background-color', dlcabgColors[i]);
    i = (i + 1) % dlcabgColors.length;
});

但是當我添加懸停功能時 ,該功能將重復所有背景色。

我想指定一種指定顏色的元素,而不是重復所有背景顏色

小提琴

一如既往地感謝您的協助!

感謝大家:)

這是你想要的嗎?
實時演示根據索引0f,懸停的索引更改顏色以匹配數組位置:

var dlC = [
    'rgb(233, 147, 26)',
    'rgb(22, 145, 190)',
    'rgb(22, 107, 162)',
    'rgb(27, 54, 71)'
];
var dlH= [
    '#000',                    /* only difference... why that? */
    'rgb(22, 145, 190)',
    'rgb(22, 107, 162)',
    'rgb(27, 54, 71)'
];

$('.abc').each(function( i ) {
   $(this).css({backgroundColor : dlC[i] })
          .on("mouseenter mouseleave",function( e ) {
              $(this).css({backgroundColor : e.type=="mouseenter" ? dlH[i] : dlC[i] });
          });
});

? : ? :我使用的是三元運算符。 如果您不知道邏輯如何工作,可以使用Goog。

您應該僅使用CSS來執行此操作,唯一需要做的就是為其創建適當的類,然后將其添加到元素中。 即:

var totalColors = 4;

$('.abc').each(function(i, e) {
    $(this).addClass("color"+i%totalColors);
});

.color1:hover { background: #0FF }
.color2:hover { background: #FF0 }
.color3:hover { background: #0F0 }
.color0:hover { background: #F00 }

編輯:較小的修復,這是一個小提琴: http : //jsfiddle.net/CxmGp/

Edit2:您還可以直接通過javascript生成css類: 如何在JavaScript中動態創建CSS類並應用?

暫無
暫無

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

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