jQuery mouseenter功能 - 如果颜色尚未改变颜色

时间:2014-04-05 13:36:33

标签: javascript jquery html css web

所以,我对jQuery不是很流利,而且我在其中编写了一些代码,看起来并不像它有效。这是我的代码;

$(document).ready(function() {
    $("#loginSelector").mouseenter(function() {
        if $("#loginSelector").style.backgroundColor != "#3064CA" {
            $("#loginSelector").style.backgroundColor = "#3064CA";
        };
    });

    $("#loginSelector").mouseleave(function() {
        if $("#loginSelector").style.backgroundColor != "#5990DE" {
            $("#loginSelector").style.backgroundColor = "#5990DE";
        };
    });

    $("#signupSelector").mouseenter(function() {
        if $("#signupSelector").style.backgroundColor != "#3064CA" {
            $("#signupSelector").style.backgroundColor = "#3064CA";
        };
    });

    $("#signupSelector").mouseleave(function() {
        if $("#signupSelector").style.backgroundColor != "#5990DE" {
            $("#signupSelector").style.backgroundColor = "#5990DE";
        };
    });
});

我想要的代码就是检查按钮是不是某种颜色,如果它不是那种颜色并且它被悬停,它会变成另一种颜色。

2 个答案:

答案 0 :(得分:0)

尝试这一点并对其余的块执行相同操作。

$("#loginSelector").mouseenter(function() { //when hovered on
    var desiredColor = "#3064CA"; //define the desired color
    if ( $(this).css('color') === desiredColor) return; //if the element's color = the desired color, don't do anything. stop the execution
    $(this).css('color', desiredColor); //else set the desired color
});

答案 1 :(得分:0)

假设元素最初的颜色为#5990DE,我只需添加以下css:

#loginSelector, #signupSelector{
 background: #5990DE;
}
#loginSelector:hover, #signupSelector:hover{
 background: #3064CA;
}

或者,否则,

的CSS:

.onHover{
 background: #3064CA;
}
.onLeave{
 background: #5990DE;
}

脚本:

$(document).on('mouseenter', 'loginSelector , #signupSelector', function(){
 $(this).addClass('onHover').removeClass('onLeave');
}); 
$(document).on('mouseleave', '#loginSelector , #signupSelector', function(){
 $(this).addClass('onLeave').removeClass('onHover');
}); 
相关问题