为什么使用 jQuery 的 css() 函数而不是 maxHeight 或其他命名的 CSS 函数

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

本文关键字:函数 maxHeight 其他 CSS jQuery css 为什么      更新时间:2023-09-26

在阅读了jQuery的CSS文档后,它看起来与直接获取Javascript元素并通过更新属性来操作其CSS相比,它没有任何优势。我错过了什么吗?

你应该使用 jQuery css 方法,它提供了许多好处:

  • 您可以在单个.css调用中设置多个 css 属性。
  • 您可以传递整数值,它将自动转换为 px。
  • 它规范了许多跨浏览器问题。例如,我可以只使用.css('opacity', 0.8),而不必测试用户是否正在使用IE并应用丑陋的alpha解决方法。
  • 我发现$('#foo').css('prop', 'value')
    $('#foo')[0].style.prop = 'value';

更不用说.css提供了jQuery的其他功能,例如链接方法和自动迭代元素数组。

jQuery使DOM查找变得更加容易,我喜欢jQuery中的CSS函数,因为我不需要记住附加函数的名称来操作样式。我可以将 .css() 与标准 CSS 属性和值结合使用。

一个优点可能是将要设置的样式与设置它们的行为分开。 例如,也许你在其他地方动态地构建JavaScript代码中的样式。 这将允许您调整该逻辑,而无需调整应用样式的代码。

或者,您可能想制作一个"可配置"脚本,并将所有样式放入标头变量中,以分离成可配置选项的一部分。 (编写自己的jQuery插件通常涉及这一点。 您可以将应用样式的代码隐藏在文件的"请勿在此行以下修改"部分中,将可设置的属性保留在人们可以配置它们的位置。

jQuery的$.fn.css真的没有做太多事情。我的意思是,这是源函数本身:

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 );
    }
}

哦,我想当我说"什么都不做"时,我的意思是它规范化名称,以便您可以使用hyphen-notation而不是camelCase,支持跨浏览器兼容性opacity并在返回适当的值之前规范化float的属性名称。

我想我也掩盖了这样一个事实,即这只是函数的访问器版本,突变器方法是:

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 ];
    }
}
因此,总而言之,优点

是您在尝试动态设置HTML元素样式时不必担心跨浏览器问题,因为专用的jQuery开发人员已经将所有内容很好地规范化为一个函数。

来自 jQuery 版本 1.7.2 的代码

与基本的JS实现相比,有很多好处,以下是我的最爱:

  • 使用选择器 $('a').css(....) 它将把该 CSS 应用于所有与"a"匹配的选择器。否则,您必须使用循环,这将创建更多代码
  • 可以传入对象 {} 并以这种方式添加样式
  • 可以执行一个函数来计算值(如上面提到的循环)。

在我看来,所有这些都导致了更干净、更简洁的代码。