使用jquery在悬停时更改背景颜色

时间:2014-06-10 17:41:04

标签: javascript jquery css html5 css3

因为我使用可变颜色的按钮,我需要添加内联css。悬停颜色是其他变量。我不能在内联css上添加悬停选择器,所以,我必须使用js。我试着用.hover()来做这件事但是当我悬停按钮时两种颜色都消失了。

代码:

$('.btn').hover( function() {
    var $hover = $('.btn').attr('data-hover');
    $(this).css( "background", $hover );
}, function() {
    var $color = $('.btn').attr('data-color');
    $(this).css( "background", $color );
});

HTML:

<button class="btn wpb_btn-small" style="background:#00aff0;" data-color="#00aff0" data-hover="#0cbbfc">Button</button>

2 个答案:

答案 0 :(得分:1)

$('.btn').hover( function() {
    var $hover = $(this).attr('data-hover');   // <-- change to this , there are many .btn
    $(this).css({ "background-color" : $hover });  // minor change
}, function() {
    var $color = $(this).attr('data-color');  // same change
    $(this).css({ "background-color" : $color });  // minor change here
});

$('.btn')正在返回一个数组 - 如果页面上有多个数组,请使用$(this)

它们都应该是“背景颜色”或“背景”,请确保使用上次编辑,我将它们设置为相同

你甚至可能真的疯了,把它全部放在一行

$(this).css({ "background-color" : $(this).attr('data-hover') });

答案 1 :(得分:0)

您应该使用 mouseenter mouseleave 事件:

http://api.jquery.com/mouseenter/

<强> HTML

 <button class="btn wpb_btn-small" style="background:#00aff0;" data-color="#00aff0" data-hover="#0cbbfc">Button</button>

<强> JS

$(function() {
    $('.btn').mouseenter(function() {
        var bg = $(this).attr('data-hover');
        $(this).css( "background", bg );
    });

    $('.btn').mouseleave(function() {
        var bg = $(this).attr('data-color');
        $(this).css( "background", bg );
    });
});

Live Demo

更新: 使用悬停事件实际上更好,(请参阅upvoted答案:&lt;)