我应该将单位'px'添加到jQuery的css函数中的数值吗?

ins*_*ead 4 jquery integer

以下是否有任何区别?

$(elem).css({ height : 100 })

$(elem).css({ height : 100+'px' })

我在谷歌搜索了很长时间,但我找不到答案.在jquery.com上有px和只是整数值的例子......浏览器或操作系统有什么不同吗?

Fel*_*ert 7

jQuery自动将单位'px'(作为默认单位)添加到大多数css属性的所有数字,包括"height":

参见src/css.js中的第221行

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

!jQuery.cssNumber[ origName ] 排除以下css属性:

  • 信息columnCount
  • fillOpacity
  • fontWeight设置
  • lineHeight是
  • 不透明度
  • 孤儿
  • 寡妇
  • 用zIndex
  • 放大

(旁注:如果你像我一样对排除"lineHeight"感到有点惊讶:没有单位的数字将乘以当前字体大小来设置行高 - 所以属性有所不同'指定/省略单位时的"行高"