javascript - 每 5 秒加载一次随机 CSS 而无需刷新页面

标签 javascript html css random

你知道如何不刷新页面加载随机CSS吗? 我想加载一个随机样式,就像在这个线程中实现的那样:

<script>
var link = [];
link[0] = "css/0.css";
link[1] = "css/1.css";
link[2] = "css/2.css";
link[3] = "css/3.css";

$(function() {
    var style = link[Math.floor(Math.random() * link.length )];
    if (document.createStyleSheet){
        document.createStyleSheet(style);
    }else{
        $('<link />',{
            rel :'stylesheet',
            type:'text/css',
            href: style
        }).appendTo('head');
    }
});
</script>

此代码有效,但是否可以每 5 秒随机加载另一种样式而不刷新? 非常感谢。

最佳答案

使用 setInterval() 每 5 秒执行一次,并使用“document.createElement”创建新链接。

您还必须记得在添加新链接之前删除之前创建的链接。

function getLink(){
    // Find previous <link> (if exists) and remove it
    var prevLink = document.querySelector("head > link");
    if(prevLink) { 
      document.querySelector("head").removeChild(prevLink); 
    }
    
    // Get a random CSS link
    var style = links[Math.floor(Math.random() * links.length )];
  
    // Create a new <link> element and configure it
    var link = document.createElement("link");
    link.setAttribute("href", style);
    link.setAttribute("rel", "stylesheet");
    console.log(link);

    // Inject element into the DOM
    document.querySelector("head").appendChild(link);
  
    // Once the stylesheet has finished downloading, add it to the DOM
    link.addEventListener("load", function(){   
      // Now that the new stylesheet has been applied, wait 5 seconds and 
      // then replace it again:
      setTimeout(getLink, 5000);
    });
  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div i="styleMe">I'm being randomly styled.</div>

关于javascript - 每 5 秒加载一次随机 CSS 而无需刷新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42209227/

相关文章:

html - 如何增加表格中所有tds的字体大小

css - 如何在 CSS Sprite 中缩放图像

html - CSS - 如何使用简单的多级菜单

javascript - 无法将 vis 与 require.js 一起使用

javascript - 如何使用 PHP 在 Google 表格图表中排序日期?

javascript - 访问 .js 文件中的模型参数

javascript - 重新渲染次数过多

jquery - CSS JQuery PHP 菜单问题

javascript - jQuery addClass 方法

php - 使输入类型为 =“Password” 在带有 IE 的移动设备上使用数字键盘