javascript - 使用 JS 选择外部 CSS 文件

标签 javascript html css browser-feature-detection

我想使用一段 JS 中的变量来选择一个 CSS 文件。我正在研究特征检测以选择特定的 CSS。这是我用来确定屏幕分辨率的代码。我想使用“RES”或“device”来选择外部 CSS。谢谢。

function hasTouch() {
  return Modernizr.touch;
}

var RES = window.screen.availWidth

function detectDevice() {
  if (hasTouch()) {
    if (RES < 600) {
      device = 'phone';
    } else {
      device = 'tablet';
    }
  } 
  if (RES > 600 && RES < 1025) {
    device = 'Medium';
  }
  if (RES > 1025 && RES < 1367) {
    device = 'Large';
  }
  if (RES > 1367) {
    device = 'XL';
  }
  return device;
}

document.querySelector('#device').innerHTML = detectDevice();

最佳答案

使用 mediaQueries,您甚至不需要 Javascript。

http://jsfiddle.net/D6hZn/3/

HTML

<div id="device"></div>

CSS

#device:before {
    content: "phone";
}

@media (min-width: 600px) {
    #device:before {
        content: "Medium";
    }

}

@media (min-width: 1025px) {
    #device:before {
        content: "Large";
    }    
}

@media (min-width: 1367px) {
    #device:before {
        content: "XL";
    }    
}

至于触摸,我希望您可以为此使用 mediaQueries,但这不可能(目前)。使用 Modernizr

CSS

html.touch #device:after {
    content: " touch";
}

html.no-touch #device:after {
    content: " no-touch";
}

关于javascript - 使用 JS 选择外部 CSS 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24437116/

相关文章:

php - JavaScript语句执行

javascript - 有没有办法让跨平台溢出:scroll

html - 将阴影和 z-index 应用于绝对定位元素

javascript - SailsJS 和全局函数、变量

javascript - 当页面位置改变时调用 Tampermonkey 脚本

javascript - 在格式化数字后将插入符设置回原来的位置

javascript - 为什么我丢失了 iframe 的 src?

jquery - 你将如何实现这种 3d 悬停效果?

html - Font Awesome Unicode - 如何将图标一直 float 到右侧

html - 在编写文本的 Css 属性时未获得预期的输出