我计划制作一个响应速度非常快的网站。为此,我目前正在包含外部样式表。
但我只想把它包括在那些支持视口单位的浏览器中,比如vw。
那么,我该如何检测浏览器是否支持它呢。
请注意:我不想包括modernizer。
在现代浏览器中,您可以在CSS中使用@supports
来检查对各种事物的支持,包括视口单元。
在@supports
中包装您想要的任何样式,就像@media
查询一样:
@supports(height: 100vh) {
.myClass { height: 100vh; }
}
此示例测试浏览器是否支持vh
或dvh
等单元,或不存在的madeup
类型(即浏览器不知道的类型):
#supportVH::after, #supportDVH:after, #supportMadeUp:after {
content: "❌ NO";
color: white;
background-color: darkred;
display: block;
margin: 1em 0;
padding: 1em;
border: 1px solid #ccc;
}
@supports(height: 100vh) {
#supportVH::after {
content: "✅ YES";
background-color: lightgreen;
}
}
@supports(height: 100dvh) {
#supportDVH:after {
content: "✅ YES";
background-color: lightgreen;
}
}
@supports(height: 100madeup) {
#supportMadeUp:after {
content: "✅ YES";
background-color: lightgreen;
}
}
<div id="supportVH">Does your browser support <code>vh</code>?</div>
<div id="supportDVH">Does your browser support <code>dvh</code>?</div>
<div id="supportMadeUp">Does your browser support <code>madeup</code>?</div>
在JavaScript中,您可以以与CSS.supports()
:相同的方式使用它
const supportsDvh = CSS.supports('height: 100dvh');
这是Modernizr
使用的代码:
testStyles('#modernizr { width: 50vw; }', function(elem) {
var width = parseInt(window.innerWidth / 2, 10);
var compStyle = parseInt((window.getComputedStyle ?
getComputedStyle(elem, null) :
elem.currentStyle).width, 10);
Modernizr.addTest('cssvwunit', compStyle == width);
});
所以你可以做一些类似的事情。只需遵循以下步骤:
- 在
vw
中设置具有width
的元素 - 检查元素的计算
width
以匹配视口的宽度 - 如果两者相同,那么您的浏览器支持
vw
和vh
Snippet即将推出
$(function () {
elemWidth = parseInt(getComputedStyle(document.querySelector("#checkVw"), null).width, 10);
halfWidth = parseInt(window.innerWidth / 2, 10);
$("#checkVw").html("Your browser" + ((elemWidth == halfWidth) ? "" : "does not ") + " support VW and VH");
});
#checkVw { width: 50vw; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="checkVw"></div>
我检查了IE 7,结果搞砸了!;)