Detect viewport units (with modernizr or normal js) and serve appropriate stylesheet

房东的猫 提交于 2019-12-22 12:19:33

问题


I actually have an issue im trying to solve since 3 weeks. Im trying to test support for vw units and serve a seperate stylesheet when the browser doesnt support the unit I read the modernizr tutorials and am familiar with modernizr css detects but testing for vh units (viewport relative units) is something I didnt find on the net.

So basically:

Scenario 1: Browser supports vw unit then serve stylesheet A.

Scenario 2: Browser doesnt support it then serve stylesheet B.

I did find out that there is a non-core detect called Modernizr.cssvwunit but I honestly have no idea where to start or how to use in in this context.

It would be great if you help me expand my knowledge. Also if it is not too laborious a jsfiddle with an example which I could study would be very helpful.

Sincerely,

Markus

Edit: why is it firing only the else statement? http://jsfiddle.net/5saCL/10

<script>
  if (Modernizr.cssvwunit) {
    alert("This browser supports VW Units!");
  } else {
    alert("This browser does not support VW Units!");
  }
</script>

回答1:


If you look at this tutorial http://www.developphp.com/view.php?tid=1253 you find out how to change CSS style with JavasSript.

You just need to edit little bit the script to match your requirements:

<!DOCTYPE html>
<html>
<head>
<link id="pagestyle" rel="stylesheet" type="text/css" href="default.css">
<script type="text/javascript">
  if (Modernizr.cssvwunit) {
    document.getElementById('pagestyle').setAttribute('href', "styleVW.css");
  } else {
    document.getElementById('pagestyle').setAttribute('href', "style.css");
  }
</script>
</head>
<body>
<h2>Javascript Change StyleSheet Without Page Reload</h2>
<!-- no buttons needed -->
</body>
</html>

This should work.




回答2:


Are you sure you want to load two different stylesheets?

Another option is to check "Add CSS Classes" in Modernizr. This way classes are added to the html element.

<html class="no-cssvhunit">

Then do this in your CSS:

.fullscreen {
    height: 100vh;
}

.no-cssvhunit .fullscreen {
    height: 100%;
}


来源:https://stackoverflow.com/questions/24107065/detect-viewport-units-with-modernizr-or-normal-js-and-serve-appropriate-styles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!