我的CSS值不反映我的JavaScript中的值

编程入门 行业动态 更新时间:2024-10-24 08:32:56
本文介绍了我的CSS值不反映我的JavaScript中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试读取显示值( display:none; 或 display:block; )来自JavaScript的div(div id =navmenu)。但是当我在相同的html文件中设置样式值时,我能够阅读,但是当我在链接的CSS样式表中设置样式值时,它不会读取(结果只是空白)。

I'm trying to read display value (display:none; or display:block;) of a div (div id="navmenu") from JavaScript. But when I set the style values in same html file I'm able to read, but when I set the style values in the linked CSS style sheet it does not read (result is just blank).

<!DOCTYPE html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link href="styles.css" rel="stylesheet" type="text/css" media="screen" /> </head> <body> <div id="navmenu"> <p>This is a box of 250px * 250px</p> </div><!--navmenu--> <!-------------------------------------------------------------------> <script> function display(elem) { return elem.style.display; } alert(display(document.getElementById('navmenu'))); </script> <!-------------------------------------------------------------------> </body> </html>

和css

and css

#navmenu { display:block; width:250px; height:250px; background-color:#3CC; }

推荐答案

elem.style.display 属性仅报告直接在DOM对象上设置的显示属性。它不会报告从样式表继承的样式。

The elem.style.display property only reports a display property that is set directly on the DOM object. It does not report a style that is inherited from a style sheet.

要获取样式值,包括样式表中的样式值,可以使用 window.getComputedStyle()

To get a style value including those from a style sheet, you can use window.getComputedStyle().

function display(elem) { return getComputedStyle(elem, null).getPropertyValue("display"); }

更多推荐

我的CSS值不反映我的JavaScript中的值

本文发布于:2023-11-08 16:07:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569849.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:CSS   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!