如何访问HTML中的根目录? (使用/不起作用)

所以我试图用HTML访问我的根目录,但是当我使用/时,它不起作用。因此,例如,我正在尝试通过以下方式获取导航CSS:

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

奇怪的是,当我将VS Code与实时服务器扩展一起使用时,它的工作原理非常好,但是我最近才注意到,当我单独运行index.html文件时,没有一个以/ work开头的链接。我也知道这也是问题所在,因为当我删除上一行中的/时,它再次正常运行(仅适用于根目录中的主页页面)。

评论
  • 清奇文
    清奇文 回复

    尝试这个:

    ./nav.css
    

    It (I mean, ./) loads files in the same directory of index.html, same as nav.css. With VS Code, I bet ./nav.css should work for the live preview too: using an external HTTP server (such as http-server on Node.js) helps, because it takes the current directory (where index.html is) as the root and you can easily reach /nav.css. Without a live server, the relative path could be reached as I said with ./nav.css (a typical *NIX path) or simply nav.css without slashes on Windows.

  • 保莺莺
    保莺莺 回复

    As Quentin points out, if you're loading the index.html file locally without a server, the root directory will be the root of your file system. If your requirement is for the index.html file to work locally on your professor's machine without a web server, you should use relative paths.

    In order to traverse back up your file system from the current file, you can use paths that start with ../

  • 咕噜咕噜
    咕噜咕噜 回复
    当我单独运行index.html文件时,没有任何以/ work开头的链接

    If you are running index.html alone then the links starting with / will be relative to the root of your file system.

    浏览器不(也不知道)哪个目录代表您的网站项目的根目录。

    使用网络服务器。通过HTTP加载数据。