简体   繁体   中英

Why use jQuery's css() function instead of maxHeight or the other named CSS functions?

After reading jQuery's CSS documentation , it doesn't look like it offers any advantages over just getting the Javascript element directly and manipulating its CSS by updating the property. Am I missing something?

You should use the jQuery css method, it provides many benefits:

  • You can set multiple css properties inside a single .css call.
  • You can pass integer values and it will automatically convert to px.
  • It normalizes many cross-browser issues. For example, I can just use .css('opacity', 0.8) without having to test if the user is using IE and applying ugly alpha workarounds.
  • I find $('#foo').css('prop', 'value') more organized and readable than
    $('#foo')[0].style.prop = 'value';

Let alone .css provides other jQuery's functionalities, such as chaining methods and automatically iterating through element arrays.

jQuery makes DOM lookup much easier, and I like the CSS function in jQuery because I don't need to remember the names of additional function to manipulate the style. I can use .css() in conjunction with the standard CSS properties and values.

There are quite a few benefits over the base JS implementation, here are my favorites:

  • use a selector $('a').css(....) and it will apply that CSS to ALL selector matched "a"s. You would have to use a loop otherwise which would create more code
  • can pass an object {} in and it adds styles that way
  • can execute a function to compute the value (like in the loop mentioned above).

All this results in a little bit cleaner and more concise code in my opinion.

One advantage could be to separate what styles you're setting from the act of setting them. Perhaps you dynamically construct the styles in JavaScript code elsewhere, for example. This would allow you to tweak that logic without having to tweak the code that applies the styles.

Or perhaps you'd like to make a "configurable" script and put all of the styles into header variables to separate into a section of configurable options. (Writing your own jQuery plugin often involves this.) You could bury the code which applies the styles in the "do not modify below this line" section of the file, leaving the settable properties where people can configure them.

jQuery's $.fn.css really doesn't do much of anything. I mean, here's the source function itself:

css: function( elem, name, extra ) {
    var ret, hooks;

    // Make sure that we're working with the right name
    name = jQuery.camelCase( name );
    hooks = jQuery.cssHooks[ name ];
    name = jQuery.cssProps[ name ] || name;

    // cssFloat needs a special treatment
    if ( name === "cssFloat" ) {
        name = "float";
    }

    // If a hook was provided get the computed value from there
    if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
        return ret;

    // Otherwise, if a way to get the computed value exists, use that
    } else if ( curCSS ) {
        return curCSS( elem, name );
    }
}

Oh, I guess when I said "doesn't do much of anything" i really meant that it normalizes names so that you can use hyphen-notation instead of camelCase , supports cross-browser compatibility for opacity and normalizes the property name for float before returning the appropriate value.

I suppose I also glossed over the fact that this is only the accessor version of the function, the mutator method is:

style: function( elem, name, value, extra ) {
    // Don't set styles on text and comment nodes
    if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
        return;
    }

    // Make sure that we're working with the right name
    var ret, type, origName = jQuery.camelCase( name ),
        style = elem.style, hooks = jQuery.cssHooks[ origName ];

    name = jQuery.cssProps[ origName ] || origName;

    // Check if we're setting a value
    if ( value !== undefined ) {
        type = typeof value;

        // convert relative number strings (+= or -=) to relative numbers. #7345
        if ( type === "string" && (ret = rrelNum.exec( value )) ) {
            value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat( jQuery.css( elem, name ) );
            // Fixes bug #9237
            type = "number";
        }

        // Make sure that NaN and null values aren't set. See: #7116
        if ( value == null || type === "number" && isNaN( value ) ) {
            return;
        }

        // If a number was passed in, add 'px' to the (except for certain CSS properties)
        if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
            value += "px";
        }

        // If a hook was provided, use that value, otherwise just set the specified value
        if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) {
            // Wrapped to prevent IE from throwing errors when 'invalid' values are provided
            // Fixes bug #5509
            try {
                style[ name ] = value;
            } catch(e) {}
        }

    } else {
        // If a hook was provided get the non-computed value from there
        if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
            return ret;
        }

        // Otherwise just get the value from the style object
        return style[ name ];
    }
}

So, all-in-all the advantages are that you don't have to worry about cross-browser issues when trying to dynamically style HTML elements, because the dedicated jQuery devs have already normalized everything nicely into one function.

code from jQuery version 1.7.2

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