Vaadin Flow应用程序自动在亮和暗模式之间切换 [英] Vaadin Flow app switch between light and dark modes automatically

查看:80
本文介绍了Vaadin Flow应用程序自动在亮和暗模式之间切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Vaadin Flow 14随附了两个捆绑主题 Lumo Material 的明暗版本.

现在,浏览器可以向主机操作系统询问用户对亮或暗模式的偏好.

是否可以让Vaadin应用根据用户的意愿自动使用浅色或深色主题变体?

Marcus Hellberg写了有关如何切换亮/暗模式的有用文章以编程方式更改主题变体.我想知道Vaadin 14现在是否可以自动切换,因为可以从浏览器中检测到用户偏好.

如果没有,也许有人可以显示Java代码,以便从服务器端Java代码中查询用户的偏好.

解决方案

您可以使用 window.matchMedia API,以监听对 5级媒体查询.有关浏览器支持,请参见 CanIUse.com .

该CSS的媒体功能配色方案首选项具有3个可能的值:no-preferencelightdark.下面的代码在dark上查找匹配项.

  1. 将下面显示的JavaScript代码放入/frontend/prefers-color-scheme.js
  2. 在主视图上,添加注释@JsModule("prefers-color-scheme.js")

 let mm = window.matchMedia('(prefers-color-scheme: dark)');
function apply() {
    document.documentElement.setAttribute("theme",mm.matches?"dark":"");
}
mm.addListener(apply);
apply();
 

来源: https://gist.github.com/emarc/690eb2659c8b51cb895716914d65ec19

Vaadin Flow 14 ships with light and dark versions of its two bundled themes, Lumo and Material.

And now browsers can ask the host OS for the user’s preference for light or dark modes.

Is there a way to have a Vaadin app automatically use the light or dark theme variant per the user’s wishes?

Marcus Hellberg wrote a helpful post on how to switch light/dark mode theme variants programmatically. I am wondering if Vaadin 14 might be able to switch automatically now that the user preference is detectable from within the browser.

If not, perhaps Someone could show Java code for inquiring about the user’s preference from server-side Java code.

解决方案

You can use window.matchMedia API to listen for changes to the prefers-color-scheme media query standardized in Media Queries Level 5. See CanIUse.com for browser support.

That CSS media feature of color scheme preference has 3 possible values: no-preference, light, and dark. The code below looks for a match on dark.

  1. Put the JavaScript code shown below into /frontend/prefers-color-scheme.js
  2. On your main view, add the annotation @JsModule("prefers-color-scheme.js")

let mm = window.matchMedia('(prefers-color-scheme: dark)');
function apply() {
    document.documentElement.setAttribute("theme",mm.matches?"dark":"");
}
mm.addListener(apply);
apply();

Source: https://gist.github.com/emarc/690eb2659c8b51cb895716914d65ec19

这篇关于Vaadin Flow应用程序自动在亮和暗模式之间切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆