针对不同浏览器获取到css文件里相关属性的两种

网站建设 2021-07-03 08:15www.dzhlxh.cn网站建设
先看个例子

复制代码
代码如下:

<div style="font-size:100px;">1111</div>
<p>2222</p>
<style>*{font-size:50px;}</style>

此时 如果用 document.querySelector("p").style.fontSize 是获取不到50px 值的 而 document.querySelector("div").style.fontSize 返回的是100

因此可以得知document.querySelector(elements).style 只针对与标签上的属性,如果在外部css 文件中的属性如何获取?

这里介绍两个方法针对不同浏览器

1、 obj.currentStyle

2、window.getComputedStyle

复制代码
代码如下:

function getCurCss(id,porp){
var obj = document.getElementById(id);
if (obj.currentStyle) {
return obj.currentStyle[prop];
} else if (window.getComputedStyle) {
propprop = prop.replace(/([A-Z])/g, "-$1");
propprop = prop.toLowerCase();
return document.defaultView.getComputedStyle(obj, null)[prop];
}
return null;
}
getCurCss(id,"fontSize");

Copyright © 2016-2025 www.dzhlxh.cn 金源码 版权所有 Power by

网站模板下载|网络推广|微博营销|seo优化|视频营销|网络营销|微信营销|网站建设|织梦模板|小程序模板