js -- 移动端pc端自动切换

1. 判断浏览器类型
浏览器判断使用的github开源项目current-device,下面是地址:
https://github.com/matthewhudson/current-device

在浏览器中能够使用下面地址进行浏览器引入,可是加载速度慢,不建议使用,我这里是直接下载本地。
<script src="https://unpkg.com/current-device/umd/current-device.min.js"></script>
2. 根据浏览器跳转到对应的页面

这是个人项目结构:javascript

│  about_us.html
│  index.html
├─js
│      current-device.min.js
│      defalut.js
└─mobile
        about_us.html
        index.html

其实只要把移动端页面放在mobile目录下便可,而后须要在每一个页面(PC端和移动端)引入current-device.min.js和defalut.js,而后浏览器访问时,执行defalut.js的方法进行跳转。html

defalut.js内容以下:java

// 判断浏览器类型,跳转到对应的页面
if (device.mobile() && !location.pathname.startsWith("/mobile")) {
    window.location.href = location.protocol + "//" + location.host + "/mobile" + location.pathname + location.search;
} else if (device.windows() && location.pathname.startsWith("/mobile")) {
    let pathname = location.pathname;
    let pcpath = pathname.substring(("/mobile".length), pathname.length);
    window.location.href = location.protocol + "//" + location.host + pcpath + location.search;
}

defalut.js主要是根据当前浏览器的类型来增长和删除子目录,在移动端时,我就判断路径是否以 “mobile” 开头,不是我就在中间插入 “/mobile” ,在PC端一样如此操做。git

相关文章
相关标签/搜索