7

CSS,我可以写 if/else 语法了?

 3 years ago
source link: https://segmentfault.com/a/1190000040847047
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

CSS,我可以写 if/else 语法了?

发布于 10 月 28 日

作者:Kenton de Jong
译者:前端小智
来源:codingnconcept

有梦想,有干货,微信搜索 【大迁世界】 关注这个在凌晨还在刷碗的刷碗智。

本文 GitHub https://github.com/qq449245884/xiaozhi 已收录,有一线大厂面试完整考点、资料以及我的系列文章。

我在 2011 年开始写CSS的时候),从来没有怀疑过这种语言会发生多大的变化。我还记得使用PIE.htcborder-radius 适配所有浏览器,我的同事做了一个PHP脚本,生成一个PNG来圆角。

然而,在过去的几年中出现了大量的CSS新特性。其中一些语句也可以被视为if语句,比如@supports样式:

@supports (border-radius: 50%) {
  // don't use PIE.htc! {}
}

还有一个经典的媒体查询,已经存在了十多年:

@media (max-width: 1000px) {
  //maybe a mobile sized device? {}
}

还有一个新的 camp(),有点不同 :

width: clamp(1000px, 50%, 10vw);

但像这样的行为:

width: clamp(1000px >= (50% >= 10vw));

看得头疼。

但这些都可以说只是 if 语句。如果我们想要一个 if/else 语句,我们需要做这样的事情。

@media (max-width: 1000px) and (prefers-color-scheme: dark) {
   //maybe a mobile device in dark mode {}
}
@media (max-width: 1000px) and (prefers-color-scheme: light) {
   //maybe a mobile device in light mode {}
}

这很烦人。

但好消息是 在新提议的 @When 特性可以解决我们的烦恼。它这么用:

@when media(max-width: 1000px) {
   // 做点什么
}

这很酷,但更酷的是还有 else:

@when media(max-width: 1000px) {
   // 移动
} @else {
   // 平板
}

机智的你可能也想到了,那肯定还有 else if 了,没错还真有:

@when media(max-width: 1000px) {
   // 平板
} @else media(max-width: 700px) { {
   // 移动 
} @else {
   // PC
}

我们也有可能可以这样做:

@when media(max-width: 700px) {
   @when (prefers-color-scheme: dark) {
      //dark mode on mobile device
   } @else {
      //light mode on mobile device 
   }
}

我说 "可能" 是因为该特性还在提案中,但我相信最终会出来的(没出来我把头发染绿)。

目前(20211023),浏览器的支持情况是怎样的?零。少到连 Can I Use 都没有。但随着新的CSS样式不断推出,我相信我们很快就会看到它。


编辑中可能存在的bug没法实时知道,事后为了解决这些bug,花了大量的时间进行log 调试,这边顺便给大家推荐一个好用的BUG监控工具 Fundebug

原文:https://kentondejong.medium.c...

有梦想,有干货,微信搜索 【大迁世界】 关注这个在凌晨还在刷碗的刷碗智。

本文 GitHub https://github.com/qq449245884/xiaozhi 已收录,有一线大厂面试完整考点、资料以及我的系列文章。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK