Сайт содержит переключатель светлого/темного режима. Я знаю, как установить другую тему для моего сайта с помощью JavaScript и CSS.
Я делаю вызов AJAX, и в качестве ответа это строка HTML. Эта строка добавляется как дочерняя внутри DIV. Проблема в том, что я не могу контролировать то, что находится внутри этого DIV. Контент генерируется через CMS и может быть любым.
Можно ли установить темный режим и для этого случайного контента? Как запросить каждый элемент DOM и изменить его цвет фона, цвет текста? Я видел, что вы можете рассчитать, является ли цвет ярким или темным по здесь.
ОБНОВЛЕНИЕ скрипки с рабочим решением:
<script src = "https://cdn.jsdelivr.net/npm/[email protected]/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>



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Да, также можно установить темный режим для любого случайного контента. Вы можете прочитать этот хорошо написанный блог, чтобы понять -> https://dev.to/wgao19/ночной режим-с-смесью-смесью-режим-разница-23lm
Вы должны проверить Darkmode.js он основан на этой концепции и дает вам виджет для включения и выключения темного режима.
Вы можете просто добавить эту строку на свою веб-страницу, и вы получите кнопку переключения.
<script src = "https://cdn.jsdelivr.net/npm/[email protected]/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>
Если этот div должен быть частью вашей страницы, и у вас есть контроль над тем, что находится на этой странице, то это легко, просто начните предсказывать все и добавьте сотни строк CSS:
.dark .item {
background: black;
}
.light .item {
background: white;
}
или вы можете облегчить свою боль с помощью SASS или LESS или чего-то еще.
Но если ваш 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
гитхаб цветовой системы: https://github.com/netbeast/colorsys
Приведенный выше код будет переключать каждый найденный цвет. измените процент функции затемнения, чтобы добавить больше контраста.
Для вашей среды могут потребоваться некоторые настройки.
Для изображений и фоновых изображений все еще есть способы инвертировать те, которые вы можете загрузить в javascript (проблема перекрестного происхождения). Но я оставлю это на какое-то другое время, и я уверен, что люди уже решили эту проблему.
Все приведенные выше ответы неверны, я напишу здесь код для блоггеров, чтобы они применяли ночной режим в своих блогах... проверьте это в моем блоге. репетитор по хинди работает хорошо.. Работает на 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>
минимальный воспроизводимый пример отсутствует, поэтому трудно сказать, но иногда достаточно простого
.dark { filter: invert(100%); }, чтобы переключиться в темный режим.