Best way to dynamically add and remove style on elements

I am using mouseenter and mouseleave events on some elements to change their appearance. I am able to do so using either of the following two strategies:

  • $(this).css('someProperty','someValue') to add and then $(this).removeAttr('style') to remove
  • $(this).addClass('someClass') to add and then $(this).removeClass('someClass') to remove
  • What is the best way to do so?


    Definitely option 2. Styles should be defined in the stylesheet.

    There's also toggleClass , which removes the class if it's there, but adds it if it's missing.


    Note: toggleClass also lets you pass in a Boolean as the second argument, telling it whether to add or remove it (regardless of whether it currently has that class applied), so:

    $(this).toggleClass('active', true);
    

    is exactly equivalent to:

    $(this).addClass('active');
    

    This is very handy when you have a Boolean in your code already. So instead of this:

    if (isUserActive()) {
        $(this).addClass('active');
    } else {
        $(this).addClass('active');
    }
    

    You could just do this:

    $(this).toggleClass('active', isUserActive());
    

    选项2,如果你必须在JavaScript中完成它,但对于现代浏览器,你可能能够完全使用CSS :hover伪类。


    I'd strongly recommend addClass() / removeClass() , since you can add, remove and change a whole swathe of properties with minimal jQuery.

    Whereas the css() method requires you, or rather the script, to keep track of what should be changed to reflect the aesthetic change(s) to convey programmatic interaction, coupling that with the attr() method and removing the style attribute will remove all styles, even those you want the element to retain, which requires you to reassign those properties.

    So, basically, option 2 is efficient, and option 1 creates unnecessary work.

    There is, of course, always toggleClass() , which can promote further efficiency.

    链接地址: http://www.djcxy.com/p/94874.html

    上一篇: 使用javascript或jquery覆盖一个css规则

    下一篇: 动态添加和删除元素样式的最佳方法