css3颜色变量_使用css3变量和最小香草javascript实现日夜颜色切换

css3颜色变量

A recent trend in interface design is the ability to choose between light and dark themes. This improves usability and accessibility for many users, particularly those who view websites at night in darkened rooms. Giving the user choice is always a good idea.

界面设计的最新趋势是可以在浅色和深色主题之间进行选择。 这提高了许多用户的可用性和可访问性,尤其是那些晚上在黑暗的房间中浏览网站的用户。 给予用户选择总是一个好主意。

I have seen a lot of implementations that jump through some… interesting hoops to get there. I have stronger words for it, but let’s just call it “interesting”. CSS in JS, loading an entirely separate stylesheet on the fly, server-side processing… but it turns out, with the new CSS3 pseudo-states like :checked and :target, a LOT of things people use JavaScript for isn’t even JavaScript’s job anymore. Modal dialogs, tabbed subsections, and even colour switching can be handled almost entirely by CSS with very little — if any — JavaScript.

我已经看到了许多实现过程,其中包括一些有趣的过程。 我对此有更强的用语,但让我们称之为“有趣”。 JS中CSS,动态加载一个完全独立的样式表,服务器端处理……但事实证明,有了新CSS3伪状态,例如:checked和:target,人们使用JavaScript的很多东西甚至都不是JavaScript的。工作了。 模态对话框选项卡式的小节甚至颜色切换几乎可以完全由CSS来处理,而JavaScript却很少(如果有的话)。

In the case of colour switching, the only thing we actually need JavaScript for is to remember/store/restore the state across page-loads. All the rest of our heavy lifting can be done in the stylesheet based on the state of one INPUT tag!

在进行颜色切换的情况下,我们真正需要JavaScript的唯一一件事就是记住/存储/恢复页面加载之间的状态。 我们剩下的所有繁重工作都可以根据一个INPUT标签的状态在样式表中完成!

标记 (The Markup)

On the HTML side of things all we need for this is a “Faux Body” — DIV since a input cannot go before BODY — and a hidden INPUT tag before it. A “Faux Body” is just a container we treat like body and is often done in modal driven layouts so that you don’t end up with two scrollbars at once. In our case it can serve double duty for the colouration and style of the page.

在HTML方面,我们所需要做的就是一个“仿体”( DIV因为输入不能BODY之前,并且在它之前是一个隐藏的INPUT标记。 “人造车身”只是我们对待车身的容器,通常在模态驱动的布局中完成,这样您就不会一次拥有两个滚动条。 在我们的情况下,它可以为页面的颜色和样式提供双重服务。

Our INPUT and DIV:

我们的INPUTDIV

<input
type="checkbox"
id="toggle_nightAndDay"
class="toggle rememberState"
hidden
aria-hidden="true"
><div id="fauxBody">
<!-- put your page content here -->
<!-- #fauxBody --></div>

Are relatively simple. It’s a checkbox, the ID is required for a LABEL to point at, the class “toggle” is common to all hidden toggle checkboxes on a page as we may have others and simply restores them to visible in our screen media stylesheet. The hidden attribute SHOULD prevent all user-agents (a browser is a UA but a UA isn’t always a browser) from seeing or interacting with the input, but some also require the aria-hidden attribute to prevent this as well. We can make them interactable again in our screen media stylesheet by setting them to display:block, then hiding them visually by sliding it off screen.

都比较简单。 这是一个复选框, LABEL指向它需要ID,页面上所有隐藏的切换复选框都使用“ toggle”类,因为我们可能还有其他一些复选框,只是将它们恢复为在屏幕媒体样式表中可见。 hidden属性应该防止所有用户代理(浏览器是UA,但UA并不总是浏览器)看到输入或与输入进行交互,但是有些还需要aria-hidden属性也可以防止这种情况。 通过将它们设置为display:block,然后通过将其滑出屏幕将它们可视地隐藏起来,可以使它们在屏幕媒体样式表中再次可交互。

From there, anywhere in our markup — like say in the main menu — we can create an element to show as our actual toggle state using a LABEL.

从那里,在标记中的任何位置(例如主菜单中的内容),我们都可以使用LABEL创建一个元素以显示为实际的切换状态。

<label for="toggle_nightAndDay"></label> 

One of the biggest pieces of magic in HTML is that clicking on a LABEL that is FOR an INPUT, SELECT, or TEXTAREA’s ID is functionally the same as clicking on that element. As such you could put that LABEL anywhere in your markup, and clicking on it will check/uncheck our checkbox!

之一在HTML魔术最大片是在该点击LABELFOR一个INPUTSELECT ,或TEXTAREAID是在功能上相当于点击该元素上。 这样,您可以将LABEL放在标记中的任何位置,然后单击它会选中/取消选中我们的复选框!

关于屏幕媒体的注意事项 (A Note About Screen Media)

You’ll see me say “screen media” a lot, and quite literally I mean using media="screen" on your stylesheet LINK, or if you’re a moron STYLE. For example:

您会看到我经常说“屏幕媒体”,从字面上看,我的意思是在样式表LINK上使用media="screen" ,或者如果您是白痴的STYLE 。 例如:

<link
rel="stylesheet"
href="screen.css"
media="screen,projection,tv"
>

If you are linking or using inline CSS that’s just for screen media on your page without a media attribute or are sending media="all", you have failed to divine the purpose of CSS and why it is separate from HTML. You should NOT be sending your screen layout to print, or aural, or anything else.

如果要链接或使用仅用于页面上没有media属性的页面媒体的内联CSS或发送media="all" ,则您将无法确定CSS的用途以及为什么将其与HTML分开。 您应该发送屏幕布局进行打印,听觉或其他任何操作。

The older projection and tv media types are still used by a number of devices in circulation to tell them we know what we are doing, and do no harm to include. In most cases — like on the Wii or DS browsers (which are still Opera 12 based) or on many public kiosks — it behaves for them much akin to how a viewport META tells mobile “we know what we’re doing, cut it out with your goofy proprietary crap!

较旧的projectiontv媒体类型仍在许多流通中的设备中使用,以告诉他们我们知道我们在做什么,并且包含这些内容也没有害处。 在大多数情况下,例如在Wii或DS浏览器(仍基于Opera 12)或许多公共信息亭上,它的行为类似于META告诉移动设备的视口“我们知道我们在做什么,切掉它”与您愚蠢的专有废话!

YES, they are “invalid” in HTML 5 as of about a year ago… which is just SO LOVELY with no version control in the document and having been valid HTML 5 prior to that. Kind of like the mental derpitude of swapping TBODY and TFOOT at about the same time whilst making the old approach of TFOOT first invalid. An arbitrary and pointless change with no means of tracking it thanks to the “living document” BS idiocy. In case you couldn’t guess, not a fan.

是的,大约一年前,它们在HTML 5中是“无效的”……这太可爱了,文档中没有版本控制,并且在此之前是有效HTML 5。 有点像大约同时交换TBODY和TFOOT的精神扭曲,同时使TFOOT的旧方法首先无效。 多亏了“活文档” BS的惯用性,任意且毫无意义的更改无法跟踪。 万一你猜不到,那就不要迷。

It’s just one of the many things that makes having your document meet modern HTML 5 validation utterly pointless. They can go suck an egg on said validation warnings, errors, and so forth when what’s “invalid” was valid under the same doctype just a year or two ago, and is still needed for many user-agents to behave properly.

这只是使文档完全符合现代HTML 5验证的众多因素之一。 当一两年前在同一文档类型下“无效”有效时,他们可能会在上述验证警告,错误等方面大吃一惊,许多用户代理仍需要它们来使其正常工作。

ANYHOW, if you are using LINK or STYLE without the media attribute or set to “all”, you’re doing it wrong. Just like how 100% of the time you see <style> in the markup and 99% of the time you see style=””, you’re looking at those pesky “3i” of web development: Ignorance, incompetence, and ineptitude.

不管怎样,如果您使用的LINKSTYLE没有媒体属性或设置为“ all”,那么您做错了。 就像在标记中100%的时间看到<style>并在99%的时间看到style=”” ,您正在查看Web开发中令人讨厌的“ 3i”:无知,无能和无能。

CSS: (The CSS:)

CSS variables always struck me as pointless when you could just search/replace in your stylesheet. In previous implementations using the bloated time wasting ignorant trash that are CSS “pre-processors” they offered little to no legitimate benefit. To be brutally frank if they did serve a purpose it was to either let people unqualified to use CSS try and modify values, or to mollycoddle those who seem to use two to ten times the CSS needed because they never mastered grouping selectors.

当您只可以在样式表中搜索/替换CSS变量时,我总是觉得毫无意义。 在以前的实现中,使用过时的浪费时间的无知垃圾是CSS的“预处理器”,它们提供的好处很少甚至没有。 坦率地说,如果他们确实达到了一个目的,那就是要么让不合格的人尝试使用CSS来修改值,要么将那些似乎使用了CSS两倍至十倍的人混为一谈,因为他们从未掌握过分组选择器。

Worse though, in pre-processors they aren’t even variables, they’re declarations. More akin to constants or define, tou couldn’t change them on the fly from the JavaScript or in the stylesheet.

更糟糕的是,在预处理器中,它们甚至不是变量,而是声明。 与常量或定义类似,tou不能从JavaScript或样式表中即时更改它们。

Native CSS variables changed all that. When you change them either by adding more CSS using JS or in the existing stylesheet based on a selector, the whole layout changes… and you CAN assign them by pseudo-class, pseudo-states, and other such selectors, combinators, and methodologies; such as the :checked attribute on an input!

原生CSS变量改变了这一切。 当您通过使用JS添加更多CSS或在基于选择器的现有样式表中更改它们时,整个布局都会发生变化……您可以按伪类,伪状态以及其他此类选择器,组合器和方法来分配它们; 例如输入中的:checked属性!

In most tutorials and discussions on the topic of native CSS variables you’ll see a lot of people say that you should assign it to the :root pseudo-element. Many even say it should only be assigned to said element, and that’s a bald faced lie. You can assign variables to any selector and they will only apply inside it. The reason to use :root is that <html> is a render element in modern browsers underneath <body> you may want to assign said variables one level above that. Since we need to use a faux-body there’s really no reason for that, so we can assign them at body level, then assign them with a selector/combinator to our div#fauxBody

在大多数有关本机CSS变量的教程和讨论中,您会看到很多人说您应该将其分配给:root伪元素。 许多人甚至说,应该只将其分配给所述元素,这是一个秃顶的谎言。 您可以将变量分配给任何选择器,它们只会在其中使用。 使用:root的原因是<html>是现代浏览器中<body>下方的render元素,您可能希望在其上一级分配所述变量。 由于我们需要使用人造身体,因此实际上没有任何理由,因此我们可以在身体级别分配它们,然后使用选择器/组合器将它们分配给我们的div#fauxBody

Thus for our normal style variables:

因此,对于我们的普通样式变量:

body {  --hue:220;

--body-background:hsl(var(--hue), 100%, 95%);
--body-color:hsl(var(--hue), 100%, 10%);

--header-background:hsl(var(--hue), 100%, 90%);
--header-border-color:#0007;

--footer-background:var(--header-background);
--footer-border-color:var(--header-border-color);
--footer-a-color:hsla(var(--hue), 100%, 15%, 0.8);
--footer-a-hover-color:#000E;

/* etc, etc, etc */}

We assign to body, then we can use this selector to assign our “dark” skin when the checkbox is… checked.

我们分配给主体,然后在选中此复选框时可以使用此选择器分配“深色”皮肤。

#toggle_nightAndDay:checked ~ * {  --hue:240;

--body-background:hsl(var(--hue), 100%, 5%);
--body-color:hsl(var(--hue), 100%, 90%);

--header-background:hsl(var(--hue), 100%, 20%);
--header-border-color:#FFF4;

--footer-background:var(--header-background);
--footer-border-color:var(--header-border-color);
--footer-a-color:hsla(var(--hue), 100%, 90%, 0.8);
--footer-a-hover-color:#FFFE; /* etc, etc, etc */}

The use of the general sibling combinator “~” and the all element selector “*” hits not just our #fauxBody, but any siblings to it like .modal.

使用通用的同级组合器“〜”和所有元素选择器“ *”不仅会击中我们的#fauxBody#fauxBody击中任何类似.modal同级.modal

A lot of people say that you should “never” use the “all element selector” as it is somehow magically “slow”. Combined with the general sibling we are limiting its application, removing that concern.

许多人说您不应该“绝对”使用“所有元素选择器”,因为它在某种程度上神奇地“慢”了。 结合同级兄弟,我们正在限制其应用,从而消除了这种担忧。

I accepted the notion of targeting everything as “bad” being factual for a good while, but recent re-evaluations on my part is increasingly showing such statements to be bald faced lies. I’ll likely at some point do an article putting this to the test just as I did with the fictional and nonsensical “render time” argument of classes vs. selectors and combinators. Seriously, this industry seems rife with people making things up to justify their own personal pet ways of doing things.

我接受将所有内容都定位为“不好的”事实已经存在了好一会儿的观点,但是我最近的重新评估越来越多地表明这种说法是光头正言。 我可能会在某个时候写一篇文章来对此进行测试,就像我对类与选择器和组合器的虚构且荒谬的“渲染时间”参数所做的一样。 认真地说,这个行业似乎充满了人们编造东西以证明自己的个人宠物做事方式的正当性。

Also notice how I assign --hue. This way we can colour shift the whole layout quickly and easily without playing with the other values. To show this off I set the “day” version to a “cyan-blue”, but at “night” I went with “true blue”. When creating layouts other people will re-colour, using HSL and variables can make life a lot easier. You want it red? Set --hue=0; You want Green? --hue=120;

还要注意我如何分配--hue 。 这样,我们可以快速轻松地对整个布局进行颜色转换,而无需使用其他值。 为了证明这一点,我将“白天”版本设置为“蓝绿色”,但是在“晚上”我使用了“真蓝色”。 在创建布局时,其他人将重新着色,使用HSL和变量可以使工作更加轻松。 你想要红色吗? 设置--hue=0; 你想要绿色吗? --hue=120;

When it comes time to assign these colours in the page, we just do it as we would any CSS variables, for example:

当需要在页面中分配这些颜色时,我们可以像处理任何CSS变量一样进行操作,例如:

.modal,
#fauxBody {
background:var(--body-background);
color:var(--body-color);
}

For the LABEL if it was in say, our #mainMenu inside an LI.nightAndDay we could isolate it for generated content to say “day” or “night” thus:

对于LABEL如果在#mainMenu内的LI.nightAndDay我们可以将其隔离以使生成的内容说“ day”或“ night”,因此:

#mainMenu .nightAndDay label:before {
content:"Day Mode";
}#toggle_nightAndDay:checked ~ #fauxBody #mainMenu .nightAndDay label:before {
content:"Night Mode";
}

You could swap that generated content for almost any effect and content you can think of that CSS can do. Since we put the text in via generated content, it doesn’t exist for non-screen media devices only further isolating stuff that could confuse or negatively impact speech, braille, print, search engines, etc, etc.

您可以将生成的内容交换为几乎可以想到CSS效果和内容。 由于我们是通过生成的内容来输入文本,因此对于非屏幕媒体设备而言,它是不存在的,只能进一步隔离可能混淆或负面影响语音,盲文,印刷,搜索引擎等的内容。

A final tweak to make the transition from night to day look nicer:

最后的调整使从夜晚到白天的过渡看起来更好:

*,
*:after,
*:before {
transition:all 0.3s;
}

Which also uses the “all” selector. OH WELL. A small — and counterintuitive — quirk I’ve found is that “*” does NOT target generated content. Which is… not “all’ is it? Hence the :after and :before. Beware that due to nesting issues some elements in Blink (chrome-likes) will transition in a odd cascade. Still looks better than a harsh “flash” between the two extremes.

其中也使用“全部”选择​​器。 那好吧。 我发现一个小但与直觉相反的怪癖是“ *”不针对生成的内容。 哪个是……不是“全部”? 因此,:after和:before。 请注意,由于嵌套问题,眨眼中的某些元素(类似Chrome)会以奇数级联过渡。 看起来仍然比两个极端之间的刺耳“闪光”更好。

That’s 90%+ of our functionality, leaving just…

这是我们功能的90%以上,仅需…

JavaScript (The JavaScript)

On the scripting side of things all we need to do is store the state of our input. This is why I added the “rememberState” class to the INPUT as it lets us easily hook any such elements on the page. All we have to do is grab all such input with querySelectorAll, loop through them to add an onchange event listener to store the state on change, and to check to see if the state is stored.

在脚本方面,我们需要做的就是存储输入的状态。 这就是为什么我向INPUT添加“ rememberState”类的原因,因为它使我们可以轻松地将页面上的任何此类元素挂钩。 我们要做的就是使用querySelectorAll捕获所有此类输入,遍历它们以添加onchange事件侦听器以存储更改时的状态,并检查是否存储了状态。

(function() {  for (var input of document.querySelectorAll("input.rememberState")) {
input.addEventListener("change", inputRemember, false);
if (input.id) input.checked = localStorage.getItem(
"remember_" + input.id
) ? "selected" : "";
}

function inputRemember(e) {
localStorage.setItem("remember_" + e.currentTarget.id, (
e.currentTarget.checked ? "selected" : ""
));
} // inputRemember

})();

I chose “local storage” over cookies since it adds no overhead to file transfers. If one wanted you could use a cookie then have your server-side code detect if the cookie is set and if so deliver the checkbox already checked. This would eliminate the if (input.id) section of the code. As is though, it’s a nice drop-in solution.

我选择“本地存储”而不是Cookie,因为它不增加文件传输的开销。 如果希望使用cookie,则让服务器端代码检测cookie是否已设置,如果已设置,则选中已选中的复选框。 这将消除代码的if (input.id)部分。 不过,这是一个不错的嵌入式解决方案。

… and because we target by tag, this code can be automatically used to remember any checkbox or radio that has “rememberState” on it, not just the one in this codebase.

…并且由于我们按标签作为目标,因此该代码可自动用于记住上面带有“ rememberState”的任何复选框或单选框,而不仅仅是此代码库中的那个。

I put it in a IIFE to isolate scope, since modules are IMHO “risky” and don’t provide isolation where it should be declared — in the script. I dislike things that violate the separation of concerns.

我将其放在IIFE中以隔离范围,因为模块是恕我直言的“风险”,并且在脚本中未提供应声明位置的隔离。 我不喜欢违反关注点分离的事情。

Internet Explorer呢? (What About Internet Explorer?)

The what?!? Oh, that. 😫

什么?!? 哦这个。 😫

I have recently converted to letting pages “gracefully degrade” to IE by simply blocking all my CSS and scripts in said browser. They get the vanilla semantic markup with no style. I can no longer justify bending over backwards to make decade out of date browsers “behave”. If we use proper semantics, what’s good enough for screen readers, braille readers, and search engines should be good enough for browsers NOBODY should be using anymore!

我最近转换为通过简单地在浏览器中阻止我的所有CSS和脚本来让页面“正常降级”为IE。 他们获得了没有样式的香草语义标记。 我再也无法证明向后弯腰以使十年过时的浏览器“表现”出来。 如果我们用正确的语义,什么是足够好的屏幕阅读器,盲文阅读器和搜索引擎应该是浏览器NOBODY不够好 正在使用了!

A cute trick? X-UA. Set it to IE9 and magically conditional comments work again.

可爱的把戏吗? X-UA。 将其设置为IE9,然后魔术地执行条件注释。

<!-- don't even bother sending CSS to legacy IE -->
<meta
http-equiv="X-UA-Compatible"
content="IE=9"
>
<!--[if !IE]>-->
<link
rel="stylesheet"
href="screen.css"
media="screen,projection,tv"
>
<link
rel="stylesheet"
href="print.css"
media="print"
>
<!--<![endif]-->

Boom, you’re no longer sending your stylesheets to any versions of IE. I also suggest adding a warning message.

Boom,您不再将样式表发送到任何版本的IE。 我还建议添加警告消息。

<!--[if IE]>
<h2 style="color:red; display:block;" hidden aria-hidden="true">
Error, Outdated Browser Detected
</h2>
<p>
<strong style="color:red; display:block;" hidden aria-hidden="true">
You are recieving a vanilla version of this page because your browser is a decade or more out of date. For full / proper appearance, please revisit in a modern browser.
</strong>
</p>
<![endif]-->

To inform IE users of what’s happening. Being in a comment, with both “hidden” and “aria-hidden” non-visual UA’s will ignore this message (good for JAWS users in IE) whilst still displaying it on-screen thanks to the display:block;

通知IE用户正在发生的事情。 在评论中,“隐藏”和“隐藏”的非可视化UA都将忽略此消息(对IE中的JAWS用户有利),同时由于display:block;而仍在屏幕上显示该消息display:block;

Know how I said up above 99% of the time you see style=”something” you’re looking at garbage code? Say hello to that 1%.

知道我在99%以上的时间里看到style=”something”正在查看垃圾代码的style=”something”怎么说? 向那1%打个招呼。

The same can be done to our JavaScript.

可以对我们JavaScript执行相同的操作。

<!--[if !IE]>-->
<script src="nightAndDay.js"></script>
<!--<![endif]-->

It sucks to have the extra code in the markup, but in total it’s not even 1k so where’s the harm. Just don’t go overboard with it.

在标记中包含多余的代码很糟,但是总的来说甚至还不到1k,所以危害何在。 只是不要太过分。

因此,让我们看看实际情况! (So Let’s See It In Action!)

I took my modal dialog driven site demo, and turned it into a demo for this. You can see this live here:

我进行了模态对话框驱动的站点演示,并将其转换为演示。 您可以在这里实时查看:

You can switch between the two modes by clicking on “Day Mode” or “Night Mode” in the top right corner on the main menu. Be sure to check out the dummy modal dialogs for the submenu, search, and login which also get their colouration set… as does the “hamburger” version of the menu for smaller screens.

您可以通过单击主菜单右上角的“白天模式”或“夜间模式”在两种模式之间切换。 确保检查出用于子菜单,搜索和登录的虚拟模式对话框,这些对话框也会获得其颜色设置……对于较小屏幕,菜单的“汉堡”版本也是如此。

As with all my examples the directory:https://cutcodedown.com/for_others/medium_articles/nightAndDay/Is wide open for easy access to the gooey bits and pieces.

就像我所有的示例一样,该目录为: https : //cutcodedown.com/for_others/medium_articles/nightAndDay/完全开放,可以轻松访问粘稠的点点滴滴。

I’ve also placed a .rar file of the entire project in there for you folks, as well as a .txt of the markup for those gun-shy of “View Source”.

我还为大家提供了整个项目的.rar文件,以及那些“害羞的”“查看源代码”的标记.txt文件

I kept the variables CSS separate from the layout stylesheet so it’s easier for you folks to follow. In practical deployment I’d combine those down to a single file so as to save a handshake, lowering the transfer overhead without the need to play with HTTP2 “Push”.

我将CSS变量布局样式表分开,因此您可以更轻松地跟随它们。 在实际部署中,我将它们合并为一个文件,以节省握手时间,从而降低了传输开销,而无需使用HTTP2“ Push”。

利弊 (Pros and Cons)

Keeping with tradition, I’ll cover the problems with the approach first.

与传统保持一致,我将首先介绍该方法的问题。

缺点 (Disadvantages)

  1. It doesn’t work in any version of IE. Plan accordingly. There is a variant of this that doesn’t use CSS variables that can be made to work in IE9/later, but it involves making our complex “general sibling” declaration for each and every element that has colours on it. It’s a pain in the arse to implement.

    它不适用于任何版本的IE。 制定相应的计划。 这种方法的一个变体是不使用CSS变量,而该变量可以在IE9 /以后的版本中使用,但是它涉及对每个带有颜色的元素进行复杂的“一般同级”声明。 实施起来很痛苦。
  2. There can be a brief flash of the light theme on a cache-empty load when dark mode’s localstorage value is set, because the script can occasionally load / run after FCP — “First Contextual Paint”. If this is a worry or issue for you, I suggest using a cookie instead of localstorage so that the server can set the INPUT to “checked” ahead of time.

    当设置了暗模式的本地存储值时,在缓存为空的加载中,浅色主题可能会短暂闪烁,因为脚本有时会在FCP(“第一个上下文绘画”)之后加载/运行。 如果您担心或遇到问题,建议您使用Cookie而不是localstorage,以便服务器可以提前将INPUT设置为“ checked”。

  3. You cannot style the actual page BODY, and instead have to rely on a “faux body” DIV element. This means some off-the-shelf scripts that try to track the window scroll won’t work, and have to be rewritten to track the scroll position of #fauxBody instead.

    您不能为实际页面BODY样式,而必须依赖于“人造主体” DIV元素。 这意味着某些试图跟踪窗口滚动的现成脚本将无法正常工作,而必须重新#fauxBody以跟踪#fauxBody的滚动位置。

  4. The extra DIV and code in the markup, particularly if you add IE fallbacks — can add a bit of undesirable overhead both to the DOM and bandwidth. Still at under 1k of actual excess markup these concerns are easily dismissed. Particularly if you leverage semantic markup, selectors, and combinators to keep the HTML small in the first place.

    标记中额外的DIV和代码,尤其是如果您添加IE后备广告时,可能会给DOM和带宽增加一些不必要的开销。 实际超标价格仍不到1k,这些问题很容易消除。 特别是如果您利用语义标记,选择器和组合器来使HTML保持较小的位置。

好处 (Advantages)

  1. CSS does most almost all the work, making for smoother transitions and loading, and making it easier to dive into making colour changes.

    CSS几乎完成了所有工作,从而使过渡和加载更加顺畅,并使更容易深入进行颜色更改。
  2. The script at only 431 bytes adds little to no overhead and is re-usable for other checkboxes or radio-buttons you might want it to remember. It can also easily be expanded to remember actual values for other form elements.

    该脚本只有431个字节,几乎没有增加开销,并且可重用于您可能想记住的其他复选框或单选按钮。 它也可以轻松扩展以记住其他表单元素的实际值。
  3. As it targets a #fauxBody as a sibling to our INPUT, it is compatible with :target driven modal dialogs.

    由于它以#fauxBody作为我们INPUT的同级对象,因此它与:target驱动的模式对话框兼容。

  4. Through the use of the hidden attribute and aria-hidden="true" we are able to make our control elements have zero impact on non-visual and/or non-screen media UA’s navigation or reading of the page. They simply don’t exist to those devices and users where they are for all intents and purposes irrelevant.

    通过使用hidden属性和aria-hidden="true"我们可以使控件元素对UA的非可视和/或非屏幕媒体UA的导航或页面阅读产生零影响。 对于那些与所有目的和用途无关的设备和用户,它们根本就不存在。

  5. As the state inside the label can be controlled just like our variables, we can set generated content of any sort or style of any sort on it. This could be a “sun” and “moon” graphic, animations, or anything else you can do with CSS.

    由于label内部的状态可以像变量一样进行控制,因此我们可以在label上设置任何种类或样式的生成内容。 这可能是“太阳”和“月亮”的图形,动画或您可以使用CSS进行的其他任何操作。

  6. Because any LABEL pointing to our INPUT using the FOR attribute can be used to toggle it, you can actually place the label anywhere in your code you want. In a menu, separate in the header, in the footer, in the middle of your content. You can even implement multiple trigger elements!

    因为任何使用FOR属性指向INPUT LABEL都可以用来切换它,所以您实际上可以将标签放置在所需代码中的任何位置。 在菜单中,在内容中间的页眉,页脚中分开。 您甚至可以实现多个触发器元素!

进一步的可能性 (Further Possibilities)

Using checkbox or radio INPUT to control layout can be used for far more than just colours. You could let users pick a font set, change up the padding or even the layout, etc, etc. It becomes an extremely powerful and useful technique the more you think about it.

使用复选框或单选INPUT来控制布局不仅仅可以用于颜色。 您可以让用户选择字体集,更改填充甚至布局等,等等。您对它的思考越多,它就变得非常强大和有用。

All without compromise on accessibility or usability, and without having to write the kilobytes — or even megabytes — of pointless JavaScript that are traditionally associated with such functionality.

所有这些都不会影响可访问性或可用性,也不必编写传统上与此类功能相关联的无意义JavaScript的千字节甚至兆字节。

结论 (Conclusion)

With the continuing improvements to and power of CSS, many things people would dive for JavaScript as the be-all end-all solution to are increasingly becoming none of JavaScript’s business. At best JS for most visual and layout effects JavaScript should be used as an enhancement and stopgap for things CSS cannot do on their own, and not be the go-to tool for every last bit of functionality.

随着CSS的不断改进和功能的强大,人们将很多事情投向JavaScript,因为作为最终解决方案的一切最终将不再与JavaScript无关。 最好的情况下,对于大多数视觉和布局效果而言,JS应该用作JavaScript的增强和权宜之计,而不是CSS不能单独完成的事情,而不是所有最后功能的首选工具。

This further enhances our ability to maintain a separation of concerns, specifically content (HTML), presentation (CSS), and behavior (JS). Many would consider this a behavior, but said “behavior” is a matter of style control, and in an ideal world style and layout are NONE of JavaScript’s business. Too often people dive for JavaScript without thinking “what happens if scripting is blocked, or irrelevant to the UA?”.

这进一步增强了我们保持关注点分离的能力,特别是内容(HTML),表示(CSS)和行为(JS)。 很多人会认为这是一个问题,但他表示“行为”是风格控制的问题,并在一个理想的世界风格和布局是JavaScript的屁事。 人们常常无意中使用JavaScript,而没有想到“如果脚本被阻止或与UA不相关,会发生什么?”。

Likewise many apply their classes, id’s, and CSS without a lick of concern for non-screen media users. There are techniques — like this one — that give you all that visual eye-candy control, without sacrificing the accessibility needs of those who aren’t that perfect picture of health sitting there using a screen media device.

同样,许多应用类,id和CSS的人不会对非屏幕媒体用户感到担忧。 像这样的技术可以为您提供所有视觉上的视觉控制,而又不会牺牲那些坐在屏幕上使用媒体设备无法获得完美健康画面的人的可访问性需求。

This technique is powerful, relatively easy to implement, and finally gives CSS variables something useful to do.

该技术功能强大,相对易于实现,并且最终为CSS变量提供了一些有用的方法。

翻译自: https://levelup.gitconnected.com/day-night-colour-switching-using-css3-variables-and-minimal-vanilla-javascript-a54fa36c550f

css3颜色变量

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值