0

I have a problem. My script works perfectly, but I loose the CSS hover effect if I go back to the input field and delete the data inside it. I no longer see the hover effect.

Before executing the keyup function, the hover effect works correctly, but after executing the keyup function I loose the hovering no longer works IF I delete the data in the input.

Can anyone see a problem or conflict and a possible solution?

$(document).ready(function(){

   $("#r1 input").keyup(function() { 
   if($("#r1 input").val().length > 0 ) 
     $("#r1 .bx").css("background-color", "#2F2F2F").css("color", "#FFF");
   else {if($("#r1 input").val().length == 0) 
     $("#r1 .bx").css("background-color", "#E8E8E8").css("color", "#000"); }});
});

My CSS:

#r1:hover div.bx, #r1:hover input { background-color: #A9A9A9; cursor:pointer}
4

3 回答 3

2

.css() will use inline styling to change the style of your elements. This will prevent pseudo classes like :hover.

Define classes and use .addClass() and .removeClass() instead (JSFiddle):

$(document).ready(function(){
   $("#r1 input").keyup(function() {
   if($("#r1 input").val().length > 0 )
          $("#r1 .bx").removeClass('b').addClass('f');
   else {if($("#r1 input").val().length == 0)
      $("#r1 .bx").removeClass('f').addClass('b');; }});
});
#r1:hover div.bx, #r1:hover input { 
    background-color: #A9A9A9; cursor:pointer;
}

.f {background-color:#2f2f2f;color:#fff;}
.b {background-color:#e8e8e8;color:#000;}
于 2012-04-11T17:05:51.460 回答
0

Style tag (What javascript uses) always have preference over CSS rules, including :hover; you can obtain the desired effect this way:

$(document).ready(function(){

   $("#r1 input").keyup(function() { 
   if($("#r1 input").val().length > 0 ) 
     $("#r1 .bx").css("background-color", "#2F2F2F").css("color", "#FFF");
   else {
     $("#r1 .bx").removeAttr("style"); }});
});

Or you can do it better with classes

$(document).ready(function(){

   $("#r1 input").keyup(function() { 
   if($("#r1 input").val().length > 0 ) 
     $("#r1 .bx").addClass("ligth");
   else {
     $("#r1 .bx").removeClass("ligth");
}});
于 2012-04-11T17:05:27.917 回答
0

Your CSS class may be being overridden by the presence of style information on the element itself.

Rather than directly specifying colours in your keyup, add or remove a CSS class:

.hasData {color:#FFF;}

using the following:

$(document).ready(function(){
    $("#r1 input").keyup(function(ev) {
        $("#r1 .bx").toggleClass('hasData', !!$(this).val());
    });
});

Note that I'm using the 'this' from the event handler rather than searching the entire document again for the input element, and that the toggling is done with the second signature of .toggleClass() after coercing the value to boolean (so, true if non-empty).

于 2012-04-11T17:07:27.423 回答