4

有没有一种简单的方法可以使用 javascript 获取相对 url?我试图使用window.location.href,但它返回绝对路径。

我想做的是:我有两页;mobile.html 和 desktop.html。我想使用一个 javascript 文件来检测用户是在移动设备上还是桌面上(我知道,这不是一个很好的方法..),如下所示:

var is_mobile = //alot of text from http://detectmobilebrowsers.com/
                //that returns true/false, this works fine

if (is_mobile){

    if (window.location.href != "mobile.html"){
        window.location = "mobile.html";
    }
}

else {
    if (window.location.href != "desktop.html"){
        window.location ="desktop.html";
    }
}

所以绝对路径的问题在于,在测试 mobile/desktop.html 时,它们都会进入无限循环 pagerefresh..

4

4 回答 4

6
var page = window.location.pathname.split('/').pop();

if (isMobile && page !== 'mobile.html')
    window.location = 'mobile.html';
else if (!isMobile && page !== 'desktop.html')
    window.location = 'desktop.html';
于 2012-10-29T19:46:20.807 回答
1

只需测试它是否以任一 HTML 文件结尾。您可以使用正则表达式:

if(/desktop\.html$/.test(window.location.href)) {
     // code for desktop
} else if(/mobile\.html$/.test(window.location.href)) {
     // code for mobile
}
于 2012-10-29T19:21:16.647 回答
1

找出 location.href 是否以 mobile.html 结尾的另一种解决方案,而不使用正则表达式:

if(window.location.href.indexOf("mobile.html") != (window.location.href.length - "mobile.html".length)) {
  ..
}
于 2012-10-29T19:37:51.200 回答
0

URL.getRelativeURL

URL标准对象有一个防弹的公共域扩展名为getRelativeURL.

这将为您解决问题:

var loc = new URL(location.href); //get the current location
var dir = new URL(".", loc); //get the current directory
var rel = loc.getRelativeURL(dir); //relative link from dir to loc

if( rel !== "mobile.html" ){ ... }

现场试一试。 查看要点。

于 2016-08-26T12:23:04.960 回答