2014-04-05 27 views
0

所以,我不是那種流利的jQuery,我已經寫了一些代碼,看起來不像它的工作。這是我的代碼;jQuery mouseenter函數 - 如果顏色不是已經變化的顏色

$(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"; 
     }; 
    }); 
}); 

所有我想要的代碼做的是檢查,看看是否按鈕是不是一種特定的顏色,如果不是顏色,它是徘徊,它變成另一種顏色。

+1

什麼決定了按鈕的顏色(CSS,條件語句)?爲什麼你不能僅僅爲了這個目的而使用CSS? – Terry

+0

任何你不能使用CSS的原因..? –

+1

爲什麼要檢查它是否已經是特定的顏色?只要應用適合每個事件的顏色,無論是否應用。 – hasanovh

回答

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 
}); 
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'); 
});