---
title: "js的location对象介绍 "
author: "libo_591"
date: "2012-03-18T22:52:24Z"
tags: []
categories: ["Web前端"]
slug: "js-location"
draft: false
lastmod: "2012-03-16T21:57:25Z"
id: 1455689
url: "https://libo-591.iteye.com/blog/1455689"
---

在写前端JS组件时，由于组件被单独封装到一个js文件中，

而同时组件又有图片在里面的话，找图片路径就有相对路径和绝对路径2种办法。

而此时的相对路径在调用这个js的页面，所以没法写；同时相对路径的../,./../之类的，当文件夹移动后，维护起来很困难，所以无论从原则上，还是这个问题上，采用相对路径都不好。

那么，我们只能用绝对路径，但是绝对路径的名字如果非得传个参数，有点儿让人难受，这里介绍一个用js的方法取页面路径的办法。

window.location.pathname 能得到页面URL的信息，然后通过截取，即可得到想要的路径。

对于window.location属性，全部介绍如下

对于一个完整的URL，其为：

[http://localhost:88/RQLibrary/development-bundle/index.jsp?module=a&arg1=b#abcd](http://localhost:88/RQLibrary/development-bundle/index.jsp?module=a&arg1=b#abcd)

则用js时，

window.location.href -  获取整个URL

window.location.protocol - 获取协议 输出为 “http:”

window.location.host - 输出为 “localhost”

window.location.port - 输出为 “port”

window.location.pathname - 输出为 “/RQLibrary/development-bundle/index.jsp”

window.location.search - 输出为“?module=a&arg1=b”

window.location.hash - 输出为#abcd