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

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

关注公众号(月影WEB),了解更多的前后端知识;

欢迎大家关注互相交流学习;


 

猜你喜欢

转载自blog.csdn.net/qq_34297287/article/details/126824831