JavaScript获取Web应用根目录路径的方法

作者:闭包旅人

时间:2026-10-27

浏览:202

本文介绍如何使用JavaScript获取Web应用的根目录路径。通过解析window.document.location.href和pathname,利用indexOf和substring方法提取域名及项目路径部分,从而得到完整的根目录地址。

文章目录

JavaScript获取Web应用根目录路径的方法

实现代码如下:

 
<script>
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);
} 
var webpath=getRootPath(); //webpath就是目录路径变量
</script>

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章