首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何为随机HTML设置暗模式?

如何为随机HTML设置暗模式?
EN

Stack Overflow用户
提问于 2019-07-06 14:42:46
回答 3查看 2.5K关注 0票数 0

该站点包含一个亮/暗模式开关。我知道如何用JavaScript和CSS为我的站点设置不同的主题。

我进行AJAX调用,作为响应,它是一个HTML字符串。此字符串作为子字符串附加到DIV中。问题是我无法控制这个DIV里面的是什么。内容是通过CMS生成的,它可以是任何内容。

也可以为这个随机内容设置暗模式吗?如何查询每个DOM元素并更改其背景色、文本颜色?我看到你可以从这里算出颜色是亮的还是暗的

更新工作解决方案:

代码语言:javascript
运行
复制
<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: &quot;Mercury SSm A&quot;, &quot;Mercury SSm B&quot;, Georgia, Times, &quot;Times New Roman&quot;, &quot;Microsoft YaHei New&quot;, &quot;Microsoft Yahei&quot;, 微软雅黑, 宋体, 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>

https://jsfiddle.net/3Lhwyogc/

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-07-06 15:13:38

是的,也可以为任意随机内容设置暗模式。你可以阅读这个写得很好的博客来理解-> https://dev.to/wgao19/night-mode-with-mix-blend-mode-difference-23lm

您应该查看Darkmode.js,它基于这个概念,并通过给您一个小部件来打开和关闭黑暗模式。

Darkmode.js

您可以简单地添加这些行在您的网页,您将得到一个切换按钮。

代码语言:javascript
运行
复制
<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>
票数 1
EN

Stack Overflow用户

发布于 2019-07-06 15:59:15

如果这个div应该是您的页面的一部分,并且您可以控制该页面中的内容,那么很容易就可以开始预测所有内容并添加数百行CSS:

代码语言:javascript
运行
复制
.dark .item {
    background: black;
}
.light .item {
    background: white;
}

或者你可以用更少或更少的东西来减轻你的痛苦。

但是,如果您的div可能包含有自己风格的任何框和不可预测的内容,并且您无法完全控制来自该ajax的样式和脚本,那么下面是一些想法:

一种方法是做这样的事情:

代码语言:javascript
运行
复制
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 (交叉原点问题)中加载这些图像。但我把这个问题留了一段时间,我相信人们已经解决了这个问题。

票数 1
EN

Stack Overflow用户

发布于 2020-01-15 05:57:13

以上所有的答案都不是很好,我会在这里写一些代码,供博客作者在自己的博客上应用夜间模式。在我的博客印地语教师上查一下吧。100%工作,刷新页面时黑暗模式不会关闭。

代码语言:javascript
运行
复制
<!-- 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>
代码语言:javascript
运行
复制
<!-- 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}
代码语言:javascript
运行
复制
<div id='theme-switch'>
<a class='fa fa-adjust' href='javascript:void(0);' onclick='retheme()' title='Change Theme'/>
    </div>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56915096

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档