【问题标题】:What is the correct way to link the CSS/Javascript to webpage?将 CSS/Javascript 链接到网页的正确方法是什么?
【发布时间】:2026-01-26 13:05:03
【问题描述】:

我想将 css 和 javascript 文件链接到我的 asp.net 表单。 我看到了不同的方法来做到这一点。但不知道区别。

  1. /

    <link type="text/css" rel="stylesheet" href="/Content/animate.css">
    
  2. ~/

    <link type="text/css" rel="stylesheet" href="~/Content/animate.css">
    
  3. 一无所有

    <link type="text/css" rel="stylesheet" href="Content/animate.css">
    
  4. ../

    <link type="text/css" rel="stylesheet" href="../Content/animate.css">
    

什么是正确的方法,有什么区别?还请说明什么时候使用什么?

【问题讨论】:

  • “什么是正确的方式?” - 这些变化会影响用于查找资源的路径,但没有一种“正确”的方式适用于所有情况。
  • href 是文件的路径。它不会被认为是变化,因为它会根据文件的位置而改变。
  • 嘿,为什么这个问题是投票赞成? :O

标签: javascript jquery html css asp.net


【解决方案1】:

正确的方法是“2”,因为你从项目的根目录开始寻址

<link type="text/css" rel="stylesheet" href="~/Content/animate.css">

【讨论】:

    【解决方案2】:
    1. /

      这一直到根目录。如果该行的文件是example.com/folder/anotherFolder/index.html,那么该行代码将访问example.com/Content/animate.css。它才刚刚开始。

    2. ~/

      <link type="text/css" rel="stylesheet" href="~/Content/animate.css">
      

      这几乎像第一个示例一样进入根目录,但会停止一个文件夹。如果该行的文件是example.com/folder/anotherFolder/index.html,那么该行代码将访问example.com/folder/Content/animate.css

    3. 一无所有

      <link type="text/css" rel="stylesheet" href="Content/animate.css">
      

      我认为在大多数情况下,您会想要这个。它访问相对于当前文件的文件。如果该行的文件是example.com/folder/anotherFolder/index.html,那么该行代码将访问example.com/folder/anotherFolder/Content/animate.css

    4. ../

      <link type="text/css" rel="stylesheet" href="../Content/animate.css">
      

      这一项仅退出一个文件夹/级别。如果该行的文件是example.com/folder/anotherFolder/index.html,那么该行代码将访问example.com/folder/Content/animate.css

    【讨论】:

      【解决方案3】:

      不同之处在于,如果您的站点是http://example.com,并且您有一个应用程序http://exmaple.com/app1

      1. 这意味着站点的根目录。所以会变成:http://example.com/Content/animate.css

        <link type="text/css" rel="stylesheet" href="/Content/animate.css">
        
      2. “~”表示应用程序的根目录。所以它会变成:http://example.com/app1/Content/animate.css

        <link type="text/css" rel="stylesheet" href="~/Content/animate.css">
        
      3. 这是真实路径,因此根据文件的位置,它只会在同一文件夹中查找 Content 文件夹,然后查找 animate.css 文件。如果您将写入此文件的文件移动到另一个文件夹,它仍会在该新位置查找 Content 文件夹,然后查找 animate.css 文件。

        <link type="text/css" rel="stylesheet" href="Content/animate.css">
        
      4. 这是说上一个目录(从编写这行代码的文件中),然后找到 Content 文件夹,然后找到 animate.css 文件。

        <link type="text/css" rel="stylesheet" href="../Content/animate.css">
        

      每一个都有它的位置和用途。现在您知道它们的含义,您可以选择使用哪个。

      作为最后一点,

      1. 将所有不同的内容写入 html 文件。
      2. 打开 Chrome 调试器(或任何浏览器调试器)并选择“网络”选项卡。
      3. 从浏览器访问html页面
      4. 查看浏览器如何解释每个路径。您将看到浏览器使用完整的 URL 向每个请求发出请求。

      您可以随时对任何路径使用该技术,看看它会解决什么问题。

      【讨论】:

        【解决方案4】:
        <link type="text/css" rel="stylesheet" href="../Content/animate.css">
        

        当css文件在Content之前的文件夹中时使用这个

        【讨论】:

          最近更新 更多