我计划制作一个非常响应的网站。为此,我目前正在包含外部样式表。
但我只想为那些支持视口单位(如vw)的浏览器包含它。
那么,我该如何检测浏览器是否支持?
请注意:我不想包含modernizer。
但我只想为那些支持视口单位(如vw)的浏览器包含它。
那么,我该如何检测浏览器是否支持?
请注意:我不想包含modernizer。
@supports
来检查各种事物(包括视口单位)的支持情况。@media
查询类似,将任何想要的样式包装在@supports
中即可。@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
!片段即将到来...
$(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>
;)