带有 Javascript 和 CSS 的 DHTML 无法正常工作
因此,由于某种原因,这个不引人注目的 JavaScript 代码不起作用,我一生都无法弄清楚为什么它不起作用。
我动态更改 div 元素的 className,因此我希望 CSS 反映该更改。然而事实并非如此。这是简化的代码。
html:
<head>
<title>Your Page</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="us.js"></script>
</head>
<body>
<div id="wrapper">
<h1 id="title">Your Page</h1>
</div>
</body>
javascript:
window.onload = function() {
document.getElementById("wrapper").className = "2";
}
css:
#wrapper{
background-color: white;
}
#wrapper.1 {
background-color: black;
}
#wrapper.2 {
background-color: red;
}
#wrapper.3 {
background-color: blue;
}
我查看了 firebug 中的包装 div,它显示该类已更改为“2”。但是,网页并没有通过将背景颜色更改为红色来反映这一点。 (它也不适用于更改文本颜色。我尝试过。)。我知道 CSS 已正确加载。那么问题出在哪里呢?
So for some reason this unobtrusive javascript code is not working and I can't figure out for the life of me why it won't work.
I dynamically change the className of a div element and therefore I expect the CSS to reflect that change. However it doesn't. Here's the simplified code.
html:
<head>
<title>Your Page</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="us.js"></script>
</head>
<body>
<div id="wrapper">
<h1 id="title">Your Page</h1>
</div>
</body>
javascript:
window.onload = function() {
document.getElementById("wrapper").className = "2";
}
css:
#wrapper{
background-color: white;
}
#wrapper.1 {
background-color: black;
}
#wrapper.2 {
background-color: red;
}
#wrapper.3 {
background-color: blue;
}
I look at the wrapper div in firebug and it shows the class being changed to "2". However, the webpage doesn't reflect that by changing the background color to be red. (it doesn't work with changing text color either. I tried that.). I know the CSS is correctly loading. So what is the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你的 css 类名需要以字母开头,如下所示:
Your css class names need to begin with a letter, like this:
2
是无效的类名。您的班级名称不能是数字;它必须是以字母开头的字母数字字符串。2
is an invalid class name. Your class name cannot be a number; it must be an alphanumeric string starting with a letter.您是否尝试使用不同的类名?检查 哪些字符在 CSS 类名称/选择器中有效? 。 css 类名不能以数字开头。
Did you try using a different class name? Check Which characters are valid in CSS class names/selectors? . css class names cannot start with numbers.