每5秒加载随机CSS,无需刷新页面

时间:2017-02-13 16:46:55

标签: 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秒随机加载另一种样式而不刷新吗? 非常感谢。

3 个答案:

答案 0 :(得分:2)

使用 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>

答案 1 :(得分:1)

<link>加载时可能会有延迟;如果这是问题,您可以使用Promise等待新的<link>加载,然后再次致电loadCSS()

var link = ["0.css", "1.css", "2.css", "3.css"];

$(function() {
  function loadCSS() {
    return new Promise(function(resolve) {
      $("link:not(:last)").remove();
      var style = link[Math.floor(Math.random() * link.length)];
      var css = $('<link />', {
          rel: 'stylesheet',
          type: 'text/css',
          href: style
        })
        .on("load", function() {
          setTimeout(function() {
            resolve(css)
          }, 5000)
        })
        .appendTo('head');
    })
    .then(function() {
      return loadCSS()
    })
  }
  loadCSS()
});

http://plnkr.co/edit/yUEJXh1szCAGB9s7VqvM?p=preview

答案 2 :(得分:0)

也许在这附近的某个地方......

    var links = ["css/0.css", "css/1.css", "css/2.css", "css/3.css"];
    
    function setCSS(){

       var link = document.createElement('link');

       link.rel  = 'stylesheet';
       link.href = links[ Math.floor(Math.random()*links.length) ];

       document.head.link && document.head.link.remove();

       document.head.link = link;
       document.head.appendChild(link);

    }
    
    setInterval(setCSS,5000);
    
    setCSS();