how does the path work in css and js

前端 未结 4 1646
滥情空心
滥情空心 2021-01-25 08:30

These days I meet so many problems about the path in css and js. And after a few tests,I can not have a exact answer,so i ask here for help.

1 The

相关标签:
4条回答
  • 2021-01-25 08:45
    • CSS uses paths relative to the CSS file location.
    • JavaScript uses paths relative to the location of the file containing the script tag.
    0 讨论(0)
  • 2021-01-25 08:50

    CSS

    Paths in CSS are relative to the location of the stylesheet. If it is a linked stylesheet, then it is the path of the CSS file. If it is embedded in an HTML document (with the style element or attribute) then it is relative to the HTML document.

    JavaScript

    JavaScript generally manipulates other documents. Any paths mentioned depend on what manipulation was done to the document. If you use JS to add a style attribute which includes a URL, then that URL is relative to the HTML document since the style attribute is part of that.

    Where you aren't manipulating the document directly (because I'm editing this almost a decade later and things like Ajax are now common) then the path is relative to the HTML document.

    If I use the absolute path like src="/img/icon.gif" It will try to find http//localhot:8000/img/icon.gif. Of cource it will get a 404 error.

    Why "of course"? Make sure that path exists, and you have no problems. Relative URLs with absolute paths (i.e. ones starting with /) are usually the most sensible choice.

    0 讨论(0)
  • 2021-01-25 08:55

    The path is always relative to the path the file referring to it is in. So, let's say your css is in /css/mystyel.css and images are in the path /img, then you refer to that image in css with:

    background-image:url(../img/myimg.jpg)
    

    If your js in in /js/myscript.js and you are adressing it from a html-file like /somepath/somehtml.html, then you use:

    <script type="text/javascript" src="../js/myscript.js"></script>
    

    If the html was in /somepath/somotherpath/somehtml.html, you would have used src="../../js/myscript.js"

    0 讨论(0)
  • 2021-01-25 09:01

    Well

    body{backgorund-image:url(img/bg.gif);}
    

    is saying look in this directory for a folder img and the file bg.gif

    You want to go back one parent directory.

    body{backgorund-image:url(../img/bg.gif);}
    
    0 讨论(0)
提交回复
热议问题