为什么jquery / css需要一个“px”作为top属性,而不是width或height属性? [英] Why does jquery/css require a 'px' for the top property, but not for the width or height property?

查看:470
本文介绍了为什么jquery / css需要一个“px”作为top属性,而不是width或height属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下一段javascript / jquery代码:

I have the following piece of javascript/jquery code:

 var some_div = $('<div>', {});

 some_div.
    css('position', 'absolute').
    css('width' , '100').
    css('height', '100').
    css('top'   , '100px').
    css('background-color', '#ddf');

 some_div.appendTo('body');

它的位置 some_div 100像素,并将其宽度和高度设置为100像素。

which works as expected in that it positions some_div 100 pixels from the body's top and also sets its width and height to 100 pixels.

如果我改变了 top 如果省略 px ,则属性为 css('top','100'那么框忽略指定的属性。很明显, px 是顶层属性生效所必需的。

If I change the line with the top property to css('top' , '100'). i.e if I omit the px, then the box disregards the specified property. Obviously, the px is required for the top property to take effect.

我想知道为什么我不必须为框的宽度和高度指定 px

I am wondering why I don't have to specify the px for the width and the height of the box.

推荐答案

仔细阅读了源代码,它看起来像一个jQuery怪癖,而不是一个浏览器或CSS奇怪。 jQuery的css函数会对您在此函数。

Having perused the source code, it looks like a jQuery quirk rather than a browser or CSS oddity. jQuery's css function does most of its preprocessing on your supplied value in this function.

该函数以各种方式处理某些CSS异常和输入异常。一种方法是通过添加px将数字转换为字符串。这不会在你的情况下,因为你提供字符串。

The function deals with certain CSS oddities and input oddities in various ways. One way is to convert numbers into strings by adding "px". This never applies in your case because you supply strings.

jQuery还有一组钩子,在CSS值上调用之前设置它们在DOM节点。您的宽度和高度值正在增加此处以考虑< a href =http://www.quirksmode.org/css/box.html> IE5.5的框模型以及 setPositiveNumber()添加的px

jQuery also has a set of hooks which are called on CSS values before setting them on the DOM node. Your width and height values are being augmented here to take into account IE5.5's box model and the px being added by setPositiveNumber().

结论:
从顶部,底部,左右,宽度和高度样式省略px因为jQuery正在修改你的属性以支持过时的浏览器和数值,所以你通过省略px,在你的宽度和高度属性中消失了无效的CSS!

Conclusion: Omitting the 'px' from your top, bottom, left, right, width and height styles is invalid CSS. Since jQuery is modifying your attributes to support antiquated browsers and numerical values, you are getting away with invalid CSS in your width and height attributes by omitting the "px"!

以下工作:

css('top' , 100)

这篇关于为什么jquery / css需要一个“px”作为top属性,而不是width或height属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆