JS和CSS无法以html格式加载

时间:2018-09-19 08:13:04

标签: javascript html css

我一直在关注这篇文章(io's documentation),以开始构建交互式网页,但是我无法使JS和CSS正常工作。

我在Sublime中工作,我按照本教程(https://dev.to/programliftoff/create-a-basic-webpage-with-css-and-javascript--104i)通过http而不是文件系统运行它。

我已经仔细检查了五十次文件夹路径(它们只是在我的桌面上以“脚本”和“样式”形式保存在与index.html doc相同的文件夹中),并尝试在路径的开头,并以两种方式都将其斜线隔开,但是JS和CSS不会加载。我还在head和body标签之间移动了“ link rel”和“ scripts async src”行,但这似乎没有什么作用。

我的html文档看起来像这样,

<!DOCTYPE html>
<html>
 <head>
    <meta charset="utf-8">
    <title>Website</title>
    <link rel=“stylesheet” type="text/css" href=“../styles/styles.css” />
    <script async src="./scripts/index.js"></script>
 </head>
 <body>
  <h1>Hello, World</h1>
  <h4 id=‘date’></h4>
  <img src="images/IMG_4945.jpg" alt="My test image">
</html>

我的JS文档看起来像这样,

document.getElementById('date').innerHTML = new Date().toDateString();

我的CSS文档如下所示,

body {
 text-align: center;
 background-color: #ffe6e6;
}

3 个答案:

答案 0 :(得分:0)

Hard to tell without looking at your file structure, but let's assume you have it like this:

|-Project
|-----css
|---------style.css
|-----js
|---------main.js
|-----index.html

in your index.html you should be calling your css like this:

<link rel="stylesheet" href="/css/style.css" />

in UNIX based OS's (and localhost Windows) / equates to document root. It's best to do this as you're guranteed to always call that file no matter where you copy + paste code to.

Note: In Windows servers / doesn't work - not sure why. Windows just sucks I guess.

答案 1 :(得分:0)

Remove the async keyword from your script element. That isn't an asynchronous script and it modifies the DOM before it's ready.

Use jQuery $(document).ready(function() {}); or JS window.onload = function() {}; and remove that async attribute so your script is run in synch with the DOM.

In other words, you cannot edit the document before it has been created. But you are trying to do that with an async and no check for if the document is ready.

答案 2 :(得分:-2)

../ means parent folder. So:

<link rel="stylesheet" type="text/css" href="styles/styles.css" />
<script src="scripts/index.js"></script>

Double quotation marks in your code are valid? -> " Pls check it.