JS 不能在原子编辑器中工作,但 CSS 可以
JS not working in atom editor but CSS does
我已经开始使用 atom 来编写我的 HTML、CSS 和 JS 文件,但是 运行 在让 JS 与 HTML 一起工作时遇到了一些问题文档。我有以下代码和相应的文件名:
代码:
var h1 = document.querySelector('h1');
h1.onclick = function(){
this.classList.add('highlight');
}
CSS:
.highlight {
color: white;
background-color: blue;
}
h1 {
font-style: italic;
}
<html>
<head>
<title>Applying Multiple Styles</title>
</head>
<body>
<h1>Highlight this element on a click</h1>
</body>
</html>
通过 chrome 打开文件时,我看到:
将标题显示为斜体,这意味着 CSS 有效,但是单击文本后,它不会像 JS 所说的那样改变颜色,因此 JS 不起作用,但 CSS 呢?有什么想法吗?
您正在将脚本加载到 <head>
中,因此您的脚本会在正文呈现之前进行评估,并且您的 h1
在执行时不存在。为了在正文呈现后评估您的脚本,您可以将 script
标记放在正文的末尾:
<html>
<head>
<link href="styles.css" rel="stylesheet" type="text/css">
<title>Applying Multiple Styles</title>
</head>
<body>
<h1>Highlight this element on a click</h1>
<script src="script.js"></script>
</body>
</html>
加载脚本时 DOM 未加载
所以你不存在!
你需要把
<script src="script.js" defer></script>
或将脚本调用放在正文末尾
我已经开始使用 atom 来编写我的 HTML、CSS 和 JS 文件,但是 运行 在让 JS 与 HTML 一起工作时遇到了一些问题文档。我有以下代码和相应的文件名:
代码:
var h1 = document.querySelector('h1');
h1.onclick = function(){
this.classList.add('highlight');
}
CSS:
.highlight {
color: white;
background-color: blue;
}
h1 {
font-style: italic;
}
<html>
<head>
<title>Applying Multiple Styles</title>
</head>
<body>
<h1>Highlight this element on a click</h1>
</body>
</html>
通过 chrome 打开文件时,我看到:
将标题显示为斜体,这意味着 CSS 有效,但是单击文本后,它不会像 JS 所说的那样改变颜色,因此 JS 不起作用,但 CSS 呢?有什么想法吗?
您正在将脚本加载到 <head>
中,因此您的脚本会在正文呈现之前进行评估,并且您的 h1
在执行时不存在。为了在正文呈现后评估您的脚本,您可以将 script
标记放在正文的末尾:
<html>
<head>
<link href="styles.css" rel="stylesheet" type="text/css">
<title>Applying Multiple Styles</title>
</head>
<body>
<h1>Highlight this element on a click</h1>
<script src="script.js"></script>
</body>
</html>
加载脚本时 DOM 未加载 所以你不存在!
你需要把
<script src="script.js" defer></script>
或将脚本调用放在正文末尾