Adding hover CSS attributes via jQuery/Javascript

后端 未结 4 608
离开以前
离开以前 2020-12-06 09:10

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).ad

相关标签:
4条回答
  • 2020-12-06 09:38

    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.

    0 讨论(0)
  • 2020-12-06 09:41

    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()

    0 讨论(0)
  • 2020-12-06 09:48
    $("#someObj").hover(function(){
        $(this).css(...);
    }:);
    

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

    0 讨论(0)
  • 2020-12-06 09:50

    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");
    });
    
    0 讨论(0)
提交回复
热议问题