??判斷是不是移動設(shè)備瀏覽現(xiàn)如今各種終端越來越多贷腕,用戶可以隨時隨地在任何設(shè)備上查看優(yōu)質(zhì)的網(wǎng)頁棱貌,但是這對于前端程序員來說也是時代的考驗忘闻。
??早年間就一臺電腦箍邮,而且顯示器就那么點(diǎn)大棒动,怎么都好做糙申,現(xiàn)在···說多了全是淚。
??之前一直把在多個項目里面運(yùn)用相同功能的JS函數(shù)代碼船惨,這讓每次我們都在文件中不停地復(fù)制柜裸,后來就想著把經(jīng)常能用到的函數(shù)做成代碼庫。以后的項目只需要引用.js文件就可以了粱锐。
??想了老半天疙挺,名字想不好,也想搞個高端怜浅、大氣铐然、上檔次的,但是苦于“哥是個文盲”恶座,索性把代碼貼出來搀暑,反正都不是我寫的,我就是喜歡用跨琳。
- 判斷瀏覽器類型
//獲取瀏覽器類型
function getExploerName(){
var explorer =navigator.userAgent; var className = '';
//ie
if (explorer.indexOf("MSIE") >= 0) {
className = 'ie';
}
//firefox
else if (explorer.indexOf("Firefox") >= 0) {
className = 'Firefox';
}
//Chrome
else if(explorer.indexOf("Chrome") >= 0){
className = 'Chrome';
}
//Opera
else if(explorer.indexOf("Opera") >= 0){
className = 'Opera';
}
//Safari
else if(explorer.indexOf("Safari") >= 0){
className = 'Safari';
}
//Netscape
else if(explorer.indexOf("Netscape")>= 0) {
className = 'Netscape';
}
return className;
}
- 判斷是不是移動設(shè)備瀏覽
function isMobile() {
if((navigator.userAgent.indexOf('iPod') != -1) || (navigator.userAgent.indexOf('iPad') != -1) || (navigator.userAgent.indexOf('iPhone') != -1) || (navigator.userAgent.indexOf('Android') != -1)){
return true;
}else{
return false;
}
}
- 判斷是不是微信瀏覽器
function isWeixn(){
var ua = window.navigator.userAgent.toLowerCase();
if(ua.match(/MicroMessenger/i)=="micromessenger") {
return true;
} else {
return false;
}
}
- 判斷移動設(shè)備橫屏or豎屏
//判斷iphone自点、ipad橫屏還是豎屏
function orient() {
if (window.orientation == 90 || window.orientation == -90) {
//ipad、iphone豎屏/Andriod橫屏
$("body").attr("class", "landscape"); orientation = 'landscape';
console.log("橫屏");
return false;
} else if (window.orientation == 0 || window.orientation == 180) {
//ipad脉让、iphone橫屏桂敛;Andriod豎屏
$("body").attr("class", "portrait"); orientation = 'portrait'; console.log("豎屏");
return false;
}
}
//頁面加載時調(diào)用
$(function () { orient(); });
//用戶變化屏幕方向時調(diào)用
$(window).bind('orientationchange', function (e) { orient(); });
- 判斷移動終端類型
//判斷移動終端類型
var browser = {
versions:function(){
var u = navigator.userAgent, app = navigator.appVersion;
return ;
}(),
language:(navigator.browserLanguage || navigator.language).toLowerCase()
}
document.writeln("語言版本: "+browser.language);
document.writeln(" 是否為移動終端: "+browser.versions.mobile);
document.writeln(" ios終端: "+browser.versions.ios);
document.writeln(" android終端: "+browser.versions.android);
document.writeln(" 是否為iPhone: "+browser.versions.iPhone);
document.writeln(" 是否iPad: "+browser.versions.iPad);
document.writeln(navigator.userAgent);
類似的方法很多
分享一個使用實(shí)例:
if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
//alert(navigator.userAgent);
window.location.href ="iPhone.html";
} else if (/(Android)/i.test(navigator.userAgent)) {
//alert(navigator.userAgent);
window.location.href ="Android.html";
} else {
window.location.href ="pc.html";
}