3

我希望能够判断(width, height, margin, padding, font-size, …)页面作者是否为 DOM 元素设置了特定的 CSS 属性。我的目标是不更改已明确设置尺寸的元素,而是更改未明确设置的元素。

function isPropertySet(elem, "width")如果页面作者将宽度 CSS 属性设置为内联或通过样式表,则应返回true 。(style="width: 100px;")

这并不简单,因为布局引擎会推断出这些值,但似乎我尝试访问它们时浏览器已经提供了值。

例如,我试过getComputedStyle(elem).getPropertyValue("width"),但这会返回计算出的宽度(给定名称并不奇怪)。

样式属性,例如elem.style.width,是不够的,因为它不包括样式表中设置的属性。

在我去搜索样式表的巨大痛苦之前,有没有人有更好的方法?

谢谢!

4

3 回答 3

2

如果您想为未自定义的元素提供默认样式集,最简单的方法是创建自己的样式表并将其放在顶部,在任何其他 CSS 文件之前。这样,在别处自定义的每个元素都会覆盖您的默认样式。注意级联顺序:不仅你的样式应该在其他样式之前,而且选择器也应该足够通用。

另一方面,如果出于某种原因您想通过 JavaScript 知道元素是否是自定义的,那么这是不可能的,除非您想将特定样式与默认样式进行比较,因为默认样式可能因浏览器而异. 例如,在 Firefox 中,默认样式为<h1/>

h1 {
  display: block;
  font-size: 2em;
  font-weight: bold;
  margin: .67em 0;
}

而 Chrome 的风格略有不同:

h1 {
  display: block;
  font-size: 2em;
  -webkit-margin-before: 0.67em;
  -webkit-margin-after: 0.67em;
  -webkit-margin-start: 0px;
  -webkit-margin-end: 0px;
  font-weight: bold;
}

这会产生一个有问题的边缘情况。想象一下,我想要全部<h1/>font-weight:normal; font-size: 200%;,但是在一个特定页面上有一个特定的标题,我希望它正好是 2em 并以粗体显示。您会认为标题没有自定义,并覆盖其样式,而实际上它自定义的,大小和重量是故意设置的。

于 2012-11-22T21:52:06.770 回答
0

The best way I have found to answer this question from JavaScript is to create a temporary element, that is not attached to the dom, and read my default values from that. I then test the default values against the values read from the element I'm testing (using jQuery or getComputedStyle) - if they compare then it's a best guess they haven't been set. Obviously this has a downside in the fact that if the element has had it's property set to the exact same value as the default you can't tell the difference.

Something like this

function hasDefaultStyle(elm, prop) {
  var def = $('<'+$(elm).attr('tagName')+' />').css(prop);
  return $(elm).css('prop') == def;
}

When dealing with different dimension metrics i.e. percent, cm, em and so on - these have to be dealt with in a different way—on browsers other than FireFox at least—due to the computed problem you mention.

FireFox does the right thing in my opinion and that when you request styles from an element that hasn't been placed in the dom it returns the original values i.e. like 50%.

For more information on how to solve at least the percent problem you can see my answer here:

Determine whether element has fixed or percentage width using JavaScript

It is rather ridiculous that such methods are necessary however :/

于 2012-11-22T22:59:11.897 回答
0

如果您不担心继承样式而只担心特定的 DOM 元素,那么也许您可以动态创建特定的元素和类名(因此它只有 CSS 样式),然后使用上述方法检查它的宽度并进行比较?

于 2012-11-22T22:00:13.380 回答