js判断是移动端还是手机端来切换css从而达到适配的目的

function loadCSS(url) {
    // Remove existing stylesheets
    var head = document.head;
    var existingStylesheets = head.getElementsByTagName('link');
    for (var i = existingStylesheets.length - 1; i >= 0; i--) {
      var stylesheet = existingStylesheets[i];
      if (stylesheet.rel === 'stylesheet') {
        head.removeChild(stylesheet);
      }
    }
  
    // Create new stylesheet
    var link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = url;
  
    // Append the new stylesheet to the head
    document.head.appendChild(link);
    console.log(link)
  }
  
 

  


// 判断是否为移动设备
function isMobileDevice() {
    return (typeof window.orientation !== "undefined") || (navigator.userAgent.indexOf('IEMobile') !== -1);
  }
  

  
  if (isMobileDevice()) {
    // 执行手机端逻辑
    console.log("This is a mobile device.");
	loadCSS('./css/index.css');

  } else {
    // 执行电脑端逻辑
    console.log("This is a desktop device.");
    //  loadCSS('file:///D:/txt/css/index2.css');
	 loadCSS('./css/index2.css');
  }

isMobileDevice();
posted @ 2023-06-21 14:09  yjxQWQ  阅读(128)  评论(0编辑  收藏  举报