我试图获取元素的当前运行时样式并过滤掉具有默认值的属性。例如,使用这样的标记:
<style>
.foo { background: red }
span { font-size:30px }
</style>
<div style="color: blue">
<span id="bar" class="foo">hello</span>
</div>
我希望结果如下:
background-color: red;
color: blue;
font-size: 30px;
我尝试了window.getComputedStyle
,但它返回了很多东西,我不确定如何过滤掉默认值。任何指针都将受到赞赏。
答案 0 :(得分:6)
/**
* IE does not have `getComputedStyle`
*/
window.getComputedStyle = window.getComputedStyle || function( element ) {
return element.currentStyle;
}
/**
* get computed style for an element, excluding any default styles
*
* @param {DOM} element
* @return {object} difference
*/
function getStylesWithoutDefaults( element ) {
// creating an empty dummy object to compare with
var dummy = document.createElement( 'element-' + ( new Date().getTime() ) );
document.body.appendChild( dummy );
// getting computed styles for both elements
var defaultStyles = getComputedStyle( dummy );
var elementStyles = getComputedStyle( element );
// calculating the difference
var diff = {};
for( var key in elementStyles ) {
if(elementStyles.hasOwnProperty(key)
&& defaultStyles[ key ] !== elementStyles[ key ] )
{
diff[ key ] = elementStyles[ key ];
}
}
// clear dom
dummy.remove();
return diff;
}
/**
* usage
*/
console.log( getStylesWithoutDefaults( document.getElementById( 'bar' ) ) );
备注:强>
答案 1 :(得分:2)
使用iframe
,这是一个更强大的解决方案。此解决方案对于一次多个元素效率低下,在这种情况下,您将需要使用片段批量元素插入并传入标记名称数组。
var getDefaultStyling = function(tagName){
if(!tagName) tagName = "dummy-tag-name";
// Create dummy iframe
var iframe = document.createElement("iframe");
document.body.appendChild(iframe);
// Create element within the iframe's document
var iframeDocument = iframe.contentDocument;
var targetElement = iframeDocument.createElement(tagName);
iframeDocument.body.appendChild(targetElement);
// Grab styling (CSSStyleDeclaration is live, and all values become "" after element removal)
var styling = iframe.contentWindow.getComputedStyle(targetElement);
var clonedStyling = {};
for(var i = 0, len = styling.length; i < len; i++){
var property = styling[i];
clonedStyling[i] = property;
clonedStyling[property] = styling[property];
}
// Remove iframe
document.body.removeChild(iframe);
// Return cloned styling
return clonedStyling;
};
var getUniqueUserStyling = function(element){
var allStyling = window.getComputedStyle(element);
var defaultStyling = getDefaultStyling(element.tagName);
var userStyling = {};
for(var i = 0, len = allStyling.length; i < len; i++){
var property = allStyling[i];
var value = allStyling[property];
var defaultValue = defaultStyling[property];
if(value != defaultValue){
userStyling[property] = value;
}
}
return userStyling;
};
用法:getUniqueUserStyling(myElement)
。
答案 2 :(得分:0)
根据mattsven的回答,我构建了我认为是更现代,完整和有效的解决方案。
您要做的就是调用以节点为参数的getUserStyles方法,例如:Styles.getUserStyles(document.querySelector('#bar'))
很明显,此代码段并不是在考虑到较旧的浏览器支持的情况下制作的,因此,如果要在公共网站上使用此代码段,则应进行一些调整。
class Styles {
// Returns a dummy iframe with no styles or content
// This allows us to get default styles from the browser for an element
static getStylesIframe() {
if (typeof window.blankIframe != 'undefined') {
return window.blankIframe;
}
window.blankIframe = document.createElement('iframe');
document.body.appendChild(window.blankIframe);
return window.blankIframe;
}
// Turns a CSSStyleDeclaration into a regular object, as all values become "" after a node is removed
static getStylesObject(node, parentWindow) {
const styles = parentWindow.getComputedStyle(node);
let stylesObject = {};
for (let i = 0; i < styles.length; i++) {
const property = styles[i];
stylesObject[property] = styles[property];
}
return stylesObject;
}
// Returns a styles object with the browser's default styles for the provided node
static getDefaultStyles(node) {
const iframe = Styles.getStylesIframe();
const iframeDocument = iframe.contentDocument;
const targetElement = iframeDocument.createElement(node.tagName);
iframeDocument.body.appendChild(targetElement);
const defaultStyles = Styles.getStylesObject(targetElement, iframe.contentWindow);
targetElement.remove();
return defaultStyles;
}
// Returns a styles object with only the styles applied by the user's CSS that differ from the browser's default styles
static getUserStyles(node) {
const defaultStyles = Styles.getDefaultStyles(node);
const styles = Styles.getStylesObject(node, window);
let userStyles = {};
for (let property in defaultStyles) {
if (styles[property] != defaultStyles[property]) {
userStyles[property] = styles[property];
}
}
return userStyles;
}
};
答案 3 :(得分:0)
如果您以后需要使用getPropertyValue,可以使用以下选项
1952-02-19 00:00:00.000
1963-08-30 00:00:00.000
1937-09-19 00:00:00.000
1955-03-04 00:00:00.000
1963-07-02 00:00:00.000
1960-05-29 00:00:00.000
1958-01-09 00:00:00.000
1966-01-27 00:00:00.000
使用此功能:
var computedStyles = getComputedStyles(document.body);
var propertyValue = computedStyles.getPropertyValue("prop-name");
答案 4 :(得分:-1)
您可以使用,例如:
window.getComputedStyle(document.getElementById('bar'))
这将返回一个对象,其中包含具有id
'bar'的元素的所有计算样式。
所以,例如你可以这样做:
var styles = window.getComputedStyle(document.getElementById('bar'));
styles = "background-color:" + styles['background-color'] + ";color:" + styles['color'] + ";font-size:" + styles['font-size'] + ";";
console.log(styles);
请注意,颜色值将以RGBA格式返回。
答案 5 :(得分:-1)
这里是..使用纯javscript ..我只是添加了jquery来设置document.ready事件。
以下是代码:
$(document).ready(function () {
var div = document.getElementById('output');
var x = document.getElementById('frame').contentWindow.document.createElement('x');
document.getElementById('frame').contentWindow.document.body.appendChild(x);
var defautlStyles = window.getComputedStyle(x);
var barStyles = window.getComputedStyle(document.getElementById('bar'));
for (i = 0; i < defautlStyles.length; i++) {
if (defautlStyles["" + defautlStyles[i]] != barStyles["" + barStyles[i]]) {
var p = document.createElement('p');
p.innerText += barStyles[i] + ": " + barStyles["" + barStyles[i]];
div.appendChild(p);
}
}
});
我使用iframe为其添加元素,因此添加元素的样式不会受文档默认样式的影响。 这是 FIDDLE
希望它有所帮助...