当通过外部CSS文件应用时,如何访问CSS中的CSS属性? [英] How to access css properties in javascript when applied via external CSS file?

查看:150
本文介绍了当通过外部CSS文件应用时,如何访问CSS中的CSS属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小问题。
当我使用外部.css文件中的一些属性,例如background-image设置css规则,然后尝试使用javascript在另一个外部.js文件中访问它,它不工作。也就是说,我不为 document.getElementById(someId).style.backgroundImage获取任何值。



但是当我使用html文件中的style属性设置css规则时,它的工作原理。



所以,我的查询是不能访问cs属性在js,如果css

解决方案

您只能访问Javascript中通过Javascript设置的样式属性 style attr)。



要访问元素当前样式,您应该获取元素的 computed style

  var el = document.getElementById('hello'); 
var comp = el.currentStyle || getComputedStyle(el,null);
alert(comp.backgroundColor);请注意,在浏览器中计算的样式可能会不同(例如,颜色是正在显示的颜色) in hex或rgb),因此如果您想要统一结果,您应该规范化


I have a little problem. When I set the css rule using some property, say, background-image in an external .css file and then try to access it using javascript in another external .js file, it does not work. That is to say I do not get any value for document.getElementById(someId).style.backgroundImage.

But when I set the css rule using style attribute in html file itself, it works.

So, my query is can't I access css property in js, if css is set in external .css file.

解决方案

You can only access style properties in Javascript that have been set via Javascript (or the style attr).

To access the elements current style you should fetch the computed style of the element.

var el = document.getElementById('hello');
var comp = el.currentStyle || getComputedStyle(el, null);
alert( comp.backgroundColor );

Note, that the computed style may vary in browsers (like color being in hex or rgb) so you should normalize that if you want unified results.

这篇关于当通过外部CSS文件应用时,如何访问CSS中的CSS属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆