js 判断当前是移动端还是PC端

2022-10-28 14:28:14 浏览数 (1)

源代码:https://gitee.com/miofly/resources

代码语言:javascript复制
// 移动端兼容
;var adaptive={};(function(f,g){var h=f.document;var i=h.documentElement;var j=f.devicePixelRatio;var k=1;var l=1;function setViewport(){var a=/iphone/gi.test(f.navigator.appVersion);if(g.scaleType===2&&a||g.scaleType===3){k=j}f.devicePixelRatioValue=k;l=1/k;var b=h.querySelector('meta[name="viewport"]');var c='initial-scale=' l ', maximum-scale=' l ', minimum-scale=' l ', user-scalable=no';if(k===1){c='width=device-width, '.concat(c)}if(!a&&k!==1){c=c.concat(', target-densitydpi=device-dpi')}if(b){b.setAttribute('content',c)}else{var d=h.createElement('meta');d.setAttribute('name','viewport');d.setAttribute('content',c);if(i.firstElementChild){i.firstElementChild.appendChild(d)}else{var e=h.createElement('div');e.appendChild(d);i.appendChild(e)}}}var m=100;g.errDpr=1;function setRem(){var a;if(g.maxWidth){a=Math.min(i.getBoundingClientRect().width,g.maxWidth*k)}else{a=i.getBoundingClientRect().width}m=100*a/g.desinWidth*(g.errDpr||1);i.style.fontSize=m 'px';h.body&&(h.body.style.fontSize=g.baseFont/100 'rem');g.setRemCallback&&g.setRemCallback();g.newBase=m}var n;g.desinWidth=750;g.baseFont=28;g.reflow=function(){i.clientWidth};function checkRem(){if(/android/ig.test(f.navigator.appVersion)){var a=document.createElement('p');a.style.height='1px';a.style.width='2.5rem';a.style.visibility='hidden';document.body.appendChild(a);var b=a.offsetWidth;var c=g.newBase*2.5;if(Math.abs(c/b-1)>0.05){g.errDpr=c/b;setRem()}document.body.removeChild(a)}}g.init=function(){f.addEventListener('resize',function(){clearTimeout(n);n=setTimeout(setRem,300)},false);f.addEventListener('pageshow',function(e){if(e.persisted){clearTimeout(n);n=setTimeout(setRem,300)}},false);if(h.readyState==='complete'){h.body.style.fontSize=g.baseFont/100 'rem';checkRem()}else{h.addEventListener('DOMContentLoaded',function(e){h.body.style.fontSize=g.baseFont/100 'rem';checkRem()},false)}setViewport();setRem();i.setAttribute('data-dpr',k)};g.remToPx=function(a){return a*m}})(window,adaptive);if(typeof module!='undefined'&&module.exports){module.exports=adaptive}else if(typeof define=='function'&&define.amd){define(function(){return adaptive})}else{window.adaptive=adaptive}window['adaptive'].desinWidth=750;window['adaptive'].baseFont=28;window['adaptive'].maxWidth=750;window['adaptive'].scaleType=1;window['adaptive'].init();;
代码语言:javascript复制
<script>
  function isPc () { // 判断是移动端还是PC端
    var _$=["Win", "Mac", "X11"];
    var is_win=navigator["platform"]["indexOf"](_$[0])==0;
    var is_mac=navigator["platform"]["indexOf"](_$[1])==0;
    var is_x11=(navigator["platform"]==_$[2]);
    return is_win==1||is_mac==1||is_x11==1
  }

  alert(isPc() == true ? 'PC端' : '移动端')
</script>

0 人点赞