2017-01-09 58 views
1

我想将css和javascript文件链接到我的asp.net表单。 我看到了不同的方式来做到这一点。但不知道差异。将CSS/Javascript链接到网页的正确方法是什么?

  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"> 
    

什么是正确的方式是什么区别?请说明何时使用什么?

+3

*“什么是正确的方法是什么?” * - 这些变化会影响哪些路径用于查找资源,但没有一个适用于所有情况的“正确”方式。 – nnnnnn

+0

'href'是文件的路径。它不会被认为是一个变体,因为它会根据文件的位置而改变。 –

+3

嘿,为什么这个问题是投票结束? :o – Sylar

回答

0

所不同的是,如果你的网站是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. 之所以如此依赖于该文件是realtive路径,它只会寻找在同一个文件夹中的内容文件夹,然后animate.css文件。如果将文件写入到另一个文件夹,它仍然会在该新位置查找Content文件夹,然后查找animate.css文件。

    <link type="text/css" rel="stylesheet" href="Content/animate.css"> 
    
  4. 这话说上去一个目录(从文件只要这行代码被写入),然后找到内容文件夹,然后animate.css文件。

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

每个人都有自己的位置和使用。现在你知道他们的意思了,你可以选择使用哪一个。

最后一点,

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

您可以随时使用该技术获取任何路径以查看解决方案。

1

正确的方法是 “2”,因为您从项目的根本解决

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

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

    此去一路到根目录。如果该行的文件是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

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

使用此当CSS文件是一个文件夹内之前Content

相关问题