【问题标题】:jQuery hover each different background colorjQuery悬停每个不同的背景颜色
【发布时间】:2013-05-28 05:18:45
【问题描述】:

如何hover 每一个不同的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;
});

但是当我添加悬停功能时,该功能会重复所有背景颜色。

我要指定一个指定颜色的元素,而不是重复所有的背景颜色

The Fiddle

一如既往,感谢您的帮助!

谢谢!每个人:)

【问题讨论】:

    标签: jquery background hover


    【解决方案1】:

    这是你想要的吗?
    LIVE DEMO 根据索引 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] });
              });
    });
    

    我使用的? : 是三元运算符。如果你不知道逻辑是如何工作的,你可以谷歌一下。

    【讨论】:

    • 是的,谢谢,Roko,但是如何更改默认背景颜色是 dlHColors,而不是白色?
    • 因为元素很奇怪,我不知道为什么不能改变css,没有任何!重要的,在这个jquery工作之后,我会弄清楚
    • @MotoTony 抱歉,我有一些错误,为了更好地编辑我的代码! ;)
    • @MotoTony 删除了 index() 的东西,因为一旦我们从 each 参数返回 index (i) 就不需要它了
    【解决方案2】:

    您应该只使用 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类:How to dynamically create CSS class in JavaScript and apply?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-04-09
      • 2015-11-09
      • 1970-01-01
      • 2014-07-14
      • 2012-01-08
      • 2022-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多