你知道如何不刷新页面加载随机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/