29

「后篇」JavaScript如何获取一个元素的样式信息

 5 years ago
source link: http://developer.51cto.com/art/201811/586523.htm?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

上一篇讲了两种获取样式的方式。

1. 通过直接访问style对象

2. 通过方法getAttribute

这两种方法都没法获取用户代理或者样式表设置的样式值。今天我来讲一种跨浏览器的方式来获取所有的与DOM相关的样式值。

一. 跨浏览器方法

n2YF32F.jpg!web

currentStyle对象是一个特定于IE的对象。它包含了一个元素的所有支持的和可用的CSS属性的一个集合。它期待骆驼表示 格式的一个值 。

比如:fontFamily而不是font-family

所以,这里,如果是支持这个对象的浏览器调用的话,就使用CSSPROP。

从代码中,可以看出,其它浏览器,使用的是window.getComputedStyle方法。该方法也可以通过document.defalutView.getComputedStyle来访问。这个方法接受两个参数,元素和一个伪元素,后者通常为空(或者一个空字符串"")。

二. 获取属性的优先级

竟然是能获取所有与DOM相关的样式属性,那必然有一个优先级的问题。

<style> 
 #elem{font-size:23px;} 
</style> 
<input id ="elem" style="font-size:18px;"/> 
elem.style.fontSize = '12px'; 
console.log(getStyle(elem, "fontSize", "font-size")) 
// 输出12px 

当在几处同时设置一个属性时,getStyle方法获取永远是那个起使用的,这一点要高度关注。

getStyle取值的优先级是:

1. 动态设置的

2. 内联设置的

3. 样式表设置的

4. 浏览器默认设置的

【责任编辑:庞桂玉 TEL:(010)68476606】


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK