简体   繁体   中英

Adding hover CSS attributes via jQuery/Javascript

Some CSS styles need to be applied to an element on hover, and CSS styles have to be applied using javascript/jquery directly and not through stylesheets or $(this).addClass('someStyle') because I am injecting the DOM elements into another page.

We can apply the usual css styles using

$('#some-content').css({
    marginTop: '60px',
    display: 'inline-block'
});

How should we add the CSS styles for :hover events?


Do we have to resort to:

$('#some-content').hover(
       function(){ $(this).css('display', 'block') },
       function(){ $(this).css('display', 'none') }
)

I find using mouseenter and mouseleave to be better than hover. There's more control.

$("#somecontent").mouseenter(function() {
    $(this).css("background", "#F00").css("border-radius", "3px");
}).mouseleave(function() {
     $(this).css("background", "00F").css("border-radius", "0px");
});

Try this:

$('#some-content').hover(function(){
    $(this).css({ marginTop: '60px', display: 'inline-block' });
}, function(){
    $(this).css({ //other stuff });
});

or using classes

$('#some-content').hover(function(){
    $(this).toggleClass('newClass');
});

More info here .hover() and .toggleClass()

You should put them in a hover event:

var elem = $('#elem');

elem.hover(function () {
    // ... :hover, set styles
}, function () {
    // ... this function is called when the mouse leaves the item, set back the
    //     normal styles
});

However, I completely recommend to put your CSS in classes and use those classes in JS, you should split the languages as much as you can.

$("#someObj").hover(function(){
    $(this).css(...);
}:);

http://api.jquery.com/hover/

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