Change background color on mouseover and remove it after mouseout

前端 未结 7 1112
被撕碎了的回忆
被撕碎了的回忆 2020-12-05 10:38

I have table which class is forum. My jquery code:



        
7条回答
  •  温柔的废话
    2020-12-05 10:47

    If you don't care about IE ≤6, you could use pure CSS ...

    .forum:hover { background-color: #380606; }
    

    .forum { color: white; }
    .forum:hover { background-color: #380606 !important; }
    /* we use !important here to override specificity. see http://stackoverflow.com/q/5805040/ */
    
    #blue { background-color: blue; }
    
    
    

    Red

    Green

    Blue


    With jQuery, usually it is better to create a specific class for this style:

    .forum_hover { background-color: #380606; }
    

    and then apply the class on mouseover, and remove it on mouseout.

    $('.forum').hover(function(){$(this).toggleClass('forum_hover');});
    

    $(document).ready(function(){
      $('.forum').hover(function(){$(this).toggleClass('forum_hover');});
    });
    .forum_hover { background-color: #380606 !important; }
    
    .forum { color: white; }
    #blue { background-color: blue; }
    
    
    
    

    Red

    Green

    Blue


    If you must not modify the class, you could save the original background color in .data():

      $('.forum').data('bgcolor', '#380606').hover(function(){
        var $this = $(this);
        var newBgc = $this.data('bgcolor');
        $this.data('bgcolor', $this.css('background-color')).css('background-color', newBgc);
      });
    

    $(document).ready(function(){
      $('.forum').data('bgcolor', '#380606').hover(function(){
        var $this = $(this);
        var newBgc = $this.data('bgcolor');
        $this.data('bgcolor', $this.css('background-color')).css('background-color', newBgc);
      });
    });
    .forum { color: white; }
    #blue { background-color: blue; }
    
    
    
    

    Red

    Green

    Blue

    or

      $('.forum').hover(
        function(){
          var $this = $(this);
          $this.data('bgcolor', $this.css('background-color')).css('background-color', '#380606');
        },
        function(){
          var $this = $(this);
          $this.css('background-color', $this.data('bgcolor'));
        }
      );   
    

    $(document).ready(function(){
      $('.forum').hover(
        function(){
          var $this = $(this);
          $this.data('bgcolor', $this.css('background-color')).css('background-color', '#380606');
        },
        function(){
          var $this = $(this);
          $this.css('background-color', $this.data('bgcolor'));
        }
      );    
    });
    .forum { color: white; }
    #blue { background-color: blue; }
    
    
    
    

    Red

    Green

    Blue

提交回复
热议问题