简体   繁体   English

使用jQuery更改悬停时的背景颜色

[英]Change background color on hover with jquery

Because I am using variable color for buttons, I need to add it with inline css. 因为我为按钮使用了可变颜色,所以需要使用内联css添加它。 The hover color is other variable. 悬停颜色是其他变量。 I cant add hover selector on inline css so, I must use js. 我无法在嵌入式CSS上添加悬停选择器,因此,我必须使用js。 I have try to do it with .hover() but when I hover the button both colors desappear. 我试图用.hover()来做,但是当我将按钮悬停时,两种颜色都消失了。

The code: 编码:

$('.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: HTML:

<button class="btn wpb_btn-small" style="background:#00aff0;" data-color="#00aff0" data-hover="#0cbbfc">Button</button>
$('.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') is returning an array - if there are more then one on the page , use $(this) $('.btn')返回一个数组-如果页面上有多个,则使用$(this)

they both should be "background-color" or "background" , make sure you use the last edit where I made them the same 它们都应该是“ background-color”或“ background”,请确保在我使它们相同的地方使用上一次编辑

you could even get really crazy and put it all in one line 您甚至会变得非常疯狂,将所有内容合而为一

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

You should use mouseenter and mouseleave events: 您应该使用mouseentermouseleave事件:

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

HTML HTML

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

JS 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 现场演示

UPDATE: It's actually better using Hover event, (refer to the upvoted answer :<) 更新:实际上,使用悬停事件会更好,(请参考建议的答案:<)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM