如何使用纯DOM函数(不使用jQuery)访问DOM元素的CSS样式?

时间:2015-09-26 22:59:12

标签: javascript html css dom

出于某种原因,我无法访问HTML元素display样式的值。

这是我的JavaScript代码:

var el = document.querySelector('#warning');
console.log(el.style.display)

我的代码为"" #warning样式返回display空字符串,但它实际上是"none"

我有以下HTML:

<div id="warning">
 warning warning warning.
</div>

我有以下CSS:

#warning {
    display: none;
}

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

你在大多数情况下都做对了,但是你遇到的是大多数人第一次尝试这种情况时的挂断。

javascript中的样式对象正在寻找这个值在实际元素内部(内联)并且不直接在css代码中查找它。

要访问样式,样式必须存在于dom中。您可以查看Window.getComputedStyle()

我希望这能解释你为什么要达到这个障碍。

答案 1 :(得分:1)

如果您知道该元素是ID,我建议您使用profile(fn=None, skip=0, filename=None, immediate=False, dirs=False, sort=None, entries=40, profiler=('cProfile', 'profile', 'hotshot'), stdout=True) Mark `fn` for profiling. If `skip` is > 0, first `skip` calls to `fn` will not be profiled. If `immediate` is False, profiling results will be printed to sys.stdout on program termination. Otherwise results will be printed after each call. (If you don't want this, set stdout=False and specify a `filename` to store profile data.) If `dirs` is False only the name of the file will be printed. Otherwise the full path is used. `sort` can be a list of sort keys (defaulting to ['cumulative', 'time', 'calls']). The following ones are recognized:: 'calls' -- call count 'cumulative' -- cumulative time 'file' -- file name 'line' -- line number 'module' -- file name 'name' -- function name 'nfl' -- name/file/line 'pcalls' -- call count 'stdname' -- standard name 'time' -- internal time `entries` limits the output to the first N entries. `profiler` can be used to select the preferred profiler, or specify a sequence of them, in order of preference. The default is ('cProfile'. 'profile', 'hotshot'). If `filename` is specified, the profile stats will be stored in the named file. You can load them with pstats.Stats(filename) or use a visualization tool like RunSnakeRun. Usage:: def fn(...): ... fn = profile(fn, skip=1) If you are using Python 2.4, you should be able to use the decorator syntax:: @profile(skip=3) def fn(...): ... or just :: @profile def fn(...): ... 函数。此外 AFAIK 样式方法仅获取内联样式。我建议使用getElementById();

<强>代码

getComputedStyle();

将输出&#34;无&#34;。

示例

http://jsfiddle.net/43jLLd5L/

阅读材料

Not directly related to your question but the answer has some good points.