该站点包含一个亮/暗模式开关。我知道如何用JavaScript和CSS为我的站点设置不同的主题。
我进行AJAX调用,作为响应,它是一个HTML字符串。此字符串作为子字符串附加到DIV中。问题是我无法控制这个DIV里面的是什么。内容是通过CMS生成的,它可以是任何内容。
也可以为这个随机内容设置暗模式吗?如何查询每个DOM元素并更改其背景色、文本颜色?我看到你可以从这里算出颜色是亮的还是暗的
更新工作解决方案:
<script src="https://cdn.jsdelivr.net/npm/darkmode-js@1.3.4/lib/darkmode-js.min.js"></script>
<p
style="-webkit-tap-highlight-color: transparent; box-sizing: border-box; margin-top: 1.5em; margin-bottom: 1.5em; font-size: 1.1875em; font-family: "Mercury SSm A", "Mercury SSm B", Georgia, Times, "Times New Roman", "Microsoft YaHei New", "Microsoft Yahei", 微软雅黑, 宋体, SimSun, STXihei, 华文细黑, serif; line-height: 1.5; animation: 1000ms linear 0s 1 normal none running fadeInLorem; background-color: rgb(85, 98, 113);">
<font color="#f7f5f5">Vel elit scelerisque mauris pellentesque pulvinar pellentesque habitant morbi. Metus
aliquam eleifend mi in nulla posuere sollicitudin aliquam ultrices. Ultrices tincidunt arcu non sodales
neque. Ipsum nunc aliquet bibendum enim facilisis gravida. Consequat ac felis donec et odio. Orci sagittis
eu volutpat odio facilisis mauris. Sagittis nisl rhoncus mattis rhoncus. Vel elit scelerisque mauris
pellentesque pulvinar pellentesque habitant morbi. Phasellus egestas tellus rutrum tellus pellentesque eu
tincidunt. Non blandit massa enim nec dui nunc mattis enim. Amet nisl suscipit adipiscing bibendum est
ultricies. Porttitor massa id neque aliquam vestibulum morbi blandit cursus risus. Donec et odio
pellentesque diam volutpat commodo sed egestas egestas.</font>
</p>
<script>
var options = {
bottom: '64px', // default: '32px'
right: 'unset', // default: '32px'
left: '32px', // default: 'unset'
time: '0.5s', // default: '0.3s'
mixColor: '#fff', // default: '#fff'
backgroundColor: '#fff', // default: '#fff'
buttonColorDark: '#100f2c', // default: '#100f2c'
buttonColorLight: '#fff', // default: '#fff'
saveInCookies: false, // default: true,
label: '' // default: ''
}
const darkmode = new Darkmode(options);
darkmode.showWidget();
</script>
发布于 2019-07-06 15:13:38
是的,也可以为任意随机内容设置暗模式。你可以阅读这个写得很好的博客来理解-> https://dev.to/wgao19/night-mode-with-mix-blend-mode-difference-23lm。
您应该查看Darkmode.js
,它基于这个概念,并通过给您一个小部件来打开和关闭黑暗模式。
您可以简单地添加这些行在您的网页,您将得到一个切换按钮。
<script src="https://cdn.jsdelivr.net/npm/darkmode-js@1.3.4/lib/darkmode-js.min.js"></script>
<script>
var options = {
bottom: '64px', // default: '32px'
right: 'unset', // default: '32px'
left: '32px', // default: 'unset'
time: '0.5s', // default: '0.3s'
mixColor: '#fff', // default: '#fff'
backgroundColor: '#fff', // default: '#fff'
buttonColorDark: '#100f2c', // default: '#100f2c'
buttonColorLight: '#fff', // default: '#fff'
saveInCookies: false, // default: true,
label: '' // default: ''
}
const darkmode = new Darkmode(options);
darkmode.showWidget();
</script>
发布于 2019-07-06 15:59:15
如果这个div应该是您的页面的一部分,并且您可以控制该页面中的内容,那么很容易就可以开始预测所有内容并添加数百行CSS:
.dark .item {
background: black;
}
.light .item {
background: white;
}
或者你可以用更少或更少的东西来减轻你的痛苦。
但是,如果您的div可能包含有自己风格的任何框和不可预测的内容,并且您无法完全控制来自该ajax的样式和脚本,那么下面是一些想法:
一种方法是做这样的事情:
function lightOrDark(color) {
// Variables for red, green, blue values
var r, g, b, hsp;
// Check the format of the color, HEX or RGB?
if (color.match(/^rgb/)) {
// If HEX --> store the red, green, blue values in separate variables
color = color.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)$/);
r = color[1];
g = color[2];
b = color[3];
}
else {
// If RGB --> Convert it to HEX: http://gist.github.com/983661
color = +("0x" + color.slice(1).replace(
color.length < 5 && /./g, '$&$&'));
r = color >> 16;
g = color >> 8 & 255;
b = color & 255;
}
// HSP (Highly Sensitive Poo) equation from http://alienryderflex.com/hsp.html
hsp = Math.sqrt(
0.299 * (r * r) +
0.587 * (g * g) +
0.114 * (b * b)
);
// Using the HSP value, determine whether the color is light or dark
if (hsp>127.5) {
return 'light';
}
else {
return 'dark';
}
}
function getStyle(el, styleProp) {
var value, defaultView = (el.ownerDocument || document).defaultView;
// W3C standard way:
if (defaultView && defaultView.getComputedStyle) {
// sanitize property name to css notation
// (hypen separated words eg. font-Size)
styleProp = styleProp.replace(/([A-Z])/g, "-$1").toLowerCase();
return defaultView.getComputedStyle(el, null).getPropertyValue(styleProp);
} else if (el.currentStyle) { // IE
// sanitize property name to camelCase
styleProp = styleProp.replace(/\-(\w)/g, function(str, letter) {
return letter.toUpperCase();
});
value = el.currentStyle[styleProp];
// convert other units to pixels on IE
if (/^\d+(em|pt|%|ex)?$/i.test(value)) {
return (function(value) {
var oldLeft = el.style.left, oldRsLeft = el.runtimeStyle.left;
el.runtimeStyle.left = el.currentStyle.left;
el.style.left = value || 0;
value = el.style.pixelLeft + "px";
el.style.left = oldLeft;
el.runtimeStyle.left = oldRsLeft;
return value;
})(value);
}
return value;
}
}
function switch_color(el) {
const switchable_attrs = "color backgroundColor".split(' '); // add more properties here
for (let i in switchable_attrs) {
let attr = switchable_attrs[i];
let color = getStyle(el, attr);
console.info(attr, color, el);
if (color == "")
continue;
try {
el.style[attr] = colorsys.stringify(colorsys.darken(colorsys.parseCss(color), lightOrDark(color) == "dark" ? -0.5 : 0.5));
console.info("Color changed from " + color + " to " + el.style[attr]);
} catch(e) {
console.warn("Cannot switch color: " + color, e, el);
}
}
for (let i = 0; i < el.children.length; i++) {
switch_color(el.children[i]);
}
}
let div = document.getElementById('the-div');
switch_color(div);
getStyle函数的来源:https://stackoverflow.com/a/2664055/4987470
彩色github:https://github.com/netbeast/colorsys
上面的代码将切换它找到的所有颜色。更改暗函数的百分比以添加更多的对比度。
它可能仍然需要对你的环境进行一些调整。
对于图像和背景图像,仍然有一些方法可以使您可以在javascript (交叉原点问题)中加载这些图像。但我把这个问题留了一段时间,我相信人们已经解决了这个问题。
发布于 2020-01-15 05:57:13
以上所有的答案都不是很好,我会在这里写一些代码,供博客作者在自己的博客上应用夜间模式。在我的博客印地语教师上查一下吧。100%工作,刷新页面时黑暗模式不会关闭。
<!-- Theme Functions JS -->
<script type='text/javascript'>
//<![CDATA[
function retheme() {
var cc = document.body.className;
if (cc.indexOf("darktheme") > -1) {
document.body.className = cc.replace("darktheme", "");
if (opener) {opener.document.body.className = cc.replace("darktheme", "");}
localStorage.setItem("preferredmode", "light");
} else {
document.body.className += " darktheme";
if (opener) {opener.document.body.className += " darktheme";}
localStorage.setItem("preferredmode", "dark");
}
}
(
function setThemeMode() {
var x = localStorage.getItem("preferredmode");
if (x == "dark") {
document.body.className += " darktheme";
}
})();
//]]>
</script>
<!-- theme switch is a button icon adjust this as your icon stylesheet -->
#theme-switch{font-size:20px;position:absolute;top:0;right:35px;z-index:19}
<!-- Here is your stylesheet for dark mode editd these colors and style name except body darktheme -->
body.darktheme{color:#fff;background-color:#000}
body.darktheme .your-element-name{color:#fff;background-color:#000}
body.darktheme .lin-element-name a{color:#fff;background-color:#000}
body.darktheme #your-element-name{color:#fff;background-color:#000}
body.darktheme your-element-name ul li a{color:#fff;background-color:#000}
<div id='theme-switch'>
<a class='fa fa-adjust' href='javascript:void(0);' onclick='retheme()' title='Change Theme'/>
</div>
https://stackoverflow.com/questions/56915096
复制相似问题