首页 > 解决方案 > 你如何根据用户的机器本地时间将 webflow 的主要 css 交换到其他 Github 托管 css?

问题描述

我正在尝试使用以下脚本根据用户本地时间将 css 应用于网站:

<script>
function getStylesheet() {
      var currentTime = new Date().getHours();
      if (0 <= currentTime&&currentTime < 5) {
       document.write("<link rel='stylesheet' href='https://rawcdn.githack.com/Jacopospina/humansplusmachines/6647fd1cb01b9b756e11d50f88efd72a6e800694/night.css' type='text/css'>");
      }
      if (5 <= currentTime&&currentTime < 16) {
       document.write("<link rel='stylesheet' href='portfolio-c16909.webflow.a39b8eeda.css' type='text/css'>");
      }
      if (16 <= currentTime&&currentTime < 22) {
       document.write("<link rel='stylesheet' href='https://rawcdn.githack.com/Jacopospina/humansplusmachines/6647fd1cb01b9b756e11d50f88efd72a6e800694/afternoon.css' type='text/css'>");
      }
      if (22 <= currentTime&&currentTime <= 24) {
       document.write("<link rel='stylesheet' href='https://rawcdn.githack.com/Jacopospina/humansplusmachines/6647fd1cb01b9b756e11d50f88efd72a6e800694/night.css' type='text/css'>");
      }
}

getStylesheet();
</script>

<noscript><link href="portfolio-c16909.webflow.a39b8eeda.css" rel="stylesheet"></noscript>

基本上,我想做的是应用基于用户本地机器时间的 CSS 主题(例如,白天、下午和夜间类型的主题)。

这是我的原始 css,取自我的 repo @ GitHub(我知道下午.css 与 webflow 的主要 css 完全相同,但这很好,因为我稍后会修改它。我的主要观点是首先让脚本成功运行)。

非常感谢您的想法——非常感谢!

标签: jquerycsswebflow

解决方案


我会按照下面的方式来做。<noscript>如果您在脚本上方使用默认样式,则不需要。我不确定你的时间逻辑,也不想花太多时间在上面。

我还添加了一个间隔调用,以便当有人在页面上时样式会发生变化,并且时间恰好会结束。它仅每小时运行一次,因此可能会模糊约 59 分钟。

<link id="myDynamicStyles" href="portfolio-c16909.webflow.a39b8eeda.css" rel="stylesheet">
<script>
    function changeStyleSheets() {
        const myDynamicStyleTag = document.getElementById('myDynamicStyles');
        const currentTime = new Date().getHours();

        if( currentTime < 5 ) {
            myDynamicStyleTag.href = 'https://rawcdn.githack.com/Jacopospina/humansplusmachines/6647fd1cb01b9b756e11d50f88efd72a6e800694/night.css';
        } else if( currentTime < 16 ) {
            myDynamicStyleTag.href = 'portfolio-c16909.webflow.a39b8eeda.css';
        } else if( currentTime < 22 ) {
            myDynamicStyleTag.href = 'https://rawcdn.githack.com/Jacopospina/humansplusmachines/6647fd1cb01b9b756e11d50f88efd72a6e800694/afternoon.css';
        } else if( currentTime <= 24 ) {
            myDynamicStyleTag.href = 'https://rawcdn.githack.com/Jacopospina/humansplusmachines/6647fd1cb01b9b756e11d50f88efd72a6e800694/night.css';
        }
    }

    changeStyleSheets();
    setInterval(changeStyleSheets, 1000*60*60); // call this every hour
</script>

<h1>My headline</h1>


推荐阅读