Detect viewport units (with modernizr or normal js

2019-05-19 04:32发布

问题:

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%;
}