简体   繁体   中英

How can I change the CSS (BG Color) of a specific element with JavaScript Hover events?

Please be patient with me, as I am a fairly new programmer and am extremely unfamiliar with client-side programming. This is my first live project and I wish to do quite a few things that I do not have the knowledge of.

The page in question can be found at http://paysonfirstassembly.com/

I am attempting to accomplish a fairly simple task. I need to change the background color of a specific element (Can be referred to by ID, of course) when it is hovered over. I know that there are other methods of doing this, but frankly, my brain is fried from being sick.

Also, if it helps, I AM using JQuery.

You use CSS, not jQuery for things like this.

In your stylesheet, just add a :hover selector to the CSS style of an element. This new style deceleration gets rendered when the element is hovered:

#original_element {
  background-color: blue;
}

#original_element:hover, .hover {
  background-color: red;
}

To support those poor people with IE6 and JS (this works for those without JS too), you can use a jQuery function:

$('#original_element').hover(function() {
  $(this).addClass('hover');
}, function {
  $(this).removeClass('hover');  
});
$(ELEMENT).hover(
    function(){
        $(this).css('background-color','red');
    },
    function(){
        // this is for 'mouse-out' event
    }
);

Btw: It's better to assign css class, that has that background color set (+ any additional styles), then you can do this:

$(ELEMENT).hover(
    function(){
        // add your css class to hovered element
        $(this).addClass('highlightClass');
    },
    function(){
        // this is for 'mouse-out' event
        // and we are going to remove that highlight
        $(this).removeClass('highlightClass');
    }
);

Css class could be:

.highlightClass {background-color:yellow;}

You may look for this:

$(selector).hover(
    function() { $(this).css('background-color', 'red'); },
    function() { $(this).css('background-color', 'green'); },
);
$('#test').hover(function() {
    $(this).css('backgroundColor', 'blue')
}, function() {
    $(this).css('backgroundColor', 'red')
})

Check working example at http://jsfiddle.net/KW5mJ/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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