10.6 将 CSS 断点与 JavaScript 联系起来
如何让 js 和 css 媒体查询断点联系起来?
@media (min-width: 20rem) {
body::after {
content: "Splus";
font-size: 0;
}
}
@media (min-width: 47.5rem) {
body::after {
content: "Mplus";
font-size: 0;
}
}
@media (min-width: 62.5rem) {
body::after {
content: "Lplus";
font-size: 0;
}
}
然后在JavaScript中,我们可以阅读这个值。首先,我们将这个值赋给一个变量。
var size = window.getComputedStyle(document.body,':after').
getPropertyValue('content');
这样就可以在js中获得当前媒体查询信息了。
;(function alertSize() {
if (size.indexOf("Splus") !=-1) {
alert('I will run functions for small screens');
}
if (size.indexOf("Mplus") !=-1) {
alert('At medium sizes, a different function could run');
}
if (size.indexOf("Lplus") !=-1) {
alert('Large screen here, different functions if needed');
}
})();
10.8 采用务实的解决方案
<button class="menu-toggle js-activate-off-canvas-menu">
<span aria-label="site navigation">☰</span> menu
</button>
假设我们有一个按钮可以打开离屏菜单。我们的自然反应可能会是这么编写。
但是在有些浏览器中,button 标签并不支持 flax 布局。
其实使用 a 标签替代即可,并不用追求完美。