我想知道什么是使用Javascript在页面刷新时调用随机css文件的最佳方法?
非常感谢
我想知道什么是使用Javascript在页面刷新时调用随机css文件的最佳方法?
非常感谢
var link = [];
link[0] = "http://site.com/css/style1.css";
link[1] = "http://site.com/css/style2.css";
link[2] = "http://site.com/css/style3.css";
$(function() {
var style = link[Math.floor(Math.random() * link.length )];
$('<link />',{
rel :'stylesheet',
type:'text/css',
href: style
}).appendTo('head');
});
编辑 :谢谢Basil Siddiqui!
var link = [];
link[0] = "http://site.com/css/style1.css";
link[1] = "http://site.com/css/style2.css";
link[2] = "http://site.com/css/style3.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');
}
});
如果你正在使用PHP,你可以阅读你的CSS目录并选择一个这样的随机文件:
<?php
$css_dir = '/css';
$files = array();
foreach(glob($cssdir.'/*.css') as $file)
{
$array[] = $file;
}
echo '<link rel="stylesheet" type="text/css" href="' . array_rand($files, 1) . '">';
?>
感谢您的建议,并没有意识到这可以用一个简单的PHP行,并且实际上发现这个方法非常简短和甜蜜
<link href="/styles/<?php echo mt_rand(1, 5); ?>.css" rel="stylesheet" type="text/css"/>
在这里找到了, http://forum.mamboserver.com/showthread.php?t=61029
非常感谢
PS。 List Apart也有一种非常简单明了的切换图像的方式, http://www.alistapart.com/articles/randomizer/
附加一个 <link>
元素 document.ready
。
var randomFileName=Math.random(); // or whatever
$(document).ready(function() {
$('head').append('<link rel="stylesheet" type="text/css" href="' + randomFileName + '.css">');
});
未经测试。如上所述,服务器端脚本直接在页面的HTML中吐出随机文件名而不是使用JS技巧可能是一个更好的(读取:更兼容)的想法。
你可以通过使用javascript生成随机链接来做到这一点
<p id="demo"></p>
<script>
var r=Math.random();
var x=document.getElementById("demo")
if (r>0.5)
{
x.innerHTML="<a href='http://w3schools.com'>Visit W3Schools</a>";
}
else
{
x.innerHTML="<a href='http://wwf.org'>Visit WWF</a>";
}
</script>
如果你想使用javascript,最好的方法是以正常方式在一个文件中加载所有随机样式。
然后在所有随机css前加上一个数字,例如:
.random-1 h1 {
color: blue;
}
.random-2 h1 {
color: red;
}
/* ... etc... */
然后只需使用javascript将随机类添加到正文中。
document.getElementsByTagName('body')[0].className+=' random-' + Math.floor((Math.random() * 10) + 1);
这应该限制加载和渲染问题,您不必担心何时调用javascript。 (另外你可以选择用更多的javascript更改为另一种随机样式)
(渲染问题取决于您所做的更改类型 - 尽管这与您在许多网站上看到的DOM对象的隐藏和显示没有什么不同。)