javascript获取地址栏的绝对路径

javascript获取地址栏的绝对路径的方法代码:

// 获取地址栏的绝对路径

function getRootPath() {

    var strFullPath = window.document.location.href;

    var strPath = window.document.location.pathname;

    var pos = strFullPath.indexOf(strPath);

    var prePath = strFullPath.substring(0, pos);

    var postPath = strPath.substring(0, strPath.substr(1).indexOf('/') + 1);

    return (prePath + postPath);

    //return prePath;

}

【getRootPath】获取地址栏的绝对路径的方法名称;

【window.document.location.href】:获取当前页面地址栏的地址;

如下图:

图1

【window.document.location.pathname】:获取当前页面的路径或文件名;

如下图:

图2

【strFullPath.indexOf(strPath)】:查看当前页面的路径或文件名在在地址栏之中的位置;

如下图:

图3

【 strFullPath.substring(0, pos)】:通过当前页面的路径或文件名的位置截取页面地址栏的地址;

如下图:

图4

【strPath.substring(0, strPath.substr(1).indexOf('/') + 1)】:再次做截取;

【prePath + postPath】:最终获取地址栏的绝对路径;

如下图:

图5

这里的截图是用的本地文件打开的,而如果启动服务之后来看的话,会更加清晰。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容