简体   繁体   English

如何获得所有内联样式的列表?

[英]How can I get a list of all inline-styles?

There's an easy way to find all current attributes on an HTMLElement using el.attributes , but I can't find an equivalent for inline-styles.有一种使用el.attributes查找 HTMLElement 上所有当前属性的简单方法,但我找不到内联样式的等效项。 I've tried seeing if anyone else ran into this problem but there seems to be no relative results.我试过看看其他人是否遇到过这个问题,但似乎没有相关结果。

Doing something like this I was able to find all possible styles, but it also included all the functions and irrelevant data.做这样的事情我能够找到所有可能的样式,但它也包括所有的功能和不相关的数据。

for( var style in el.style ){ 
    console.log(el.style[style]); 
}

This is a very wasteful computation for a loop that can be as large as 300+ iterations with a potential of 100% of the inline-styles not actually set to anything.对于一个循环来说,这是一种非常浪费的计算,循环可能会多达 300 多次迭代,并且有可能 100% 的内联样式实际上并未设置为任何内容。 Is there a better way?有没有更好的办法?

Note: I did have the answer before posting this question, but I was going to ask it anyways and think it would be helpful to other people注意:在发布此问题之前我确实有答案,但无论如何我还是要问它并认为这对其他人有帮助

The style object returned by nodes has a length property which is the number of currently defined inline-styles.节点返回的样式对象有一个length属性,它是当前定义的内联样式的数量。 You can use this property to loop over the style object as an array-like structure and each index returns the name that is defined.您可以使用此属性将样式对象作为类似数组的结构进行循环,并且每个索引都返回定义的名称。

Example:例子:

for (var i = 0, l = el.style.length; i < l; i++){
    console.log(el.style[i]); // an active inline-style
}

The modern way of doing it is this:现代的做法是这样的:

 function getInlineStyle (element) { return Array.from(element.style).reduce((style, name) => { style[name] = element.style[name] return style }, {}) } const div = document.getElementById('foo') console.log(getInlineStyle(div))
 <div id="foo" style="width: 100px; margin-top: 10px;"></div>

If you only need an array of set inline CSS properties, you can simply convert the style of the element to an array with spread syntax or Array.from .如果您只需要一组内联 CSS 属性,您可以简单地将元素的style转换为具有扩展语法或Array.from的数组。

 function getInlineStyleProperties(elem){ return [...elem.style]; } console.log(getInlineStyleProperties(document.querySelector('div')));
 <div style="height: 20px; color: red;"></div>

To get an object mapping the set properties to their values, you can convert the style of the element to an array with spread syntax to get all the set properties, map over it to create an array of key-value pairs, and use Object.fromEntries to convert it to an object.要获得一个对象将集合属性映射到它们的值,您可以使用扩展语法将元素的style转换为数组以获取所有集合属性,映射它以创建键值对数组,并使用Object.fromEntries将其转换为对象。

 function getInlineStyles(elem){ return Object.fromEntries([...elem.style].map(x => [x, elem.style[x]])); } console.log(getInlineStyles(document.querySelector('div')));
 <div style="height: 20px; color: red;"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM