Rob*_*Rob 10 javascript css apache jquery server-side
我想知道什么是使用Javascript在页面刷新时调用随机css文件的最佳方法?
非常感谢
小智 8
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');
});
Run Code Online (Sandbox Code Playgroud)
编辑:谢谢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');
}
});
Run Code Online (Sandbox Code Playgroud)
如果你正在使用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) . '">';
?>
Run Code Online (Sandbox Code Playgroud)
感谢您的建议,没有意识到只需一行简单的 php 就可以实现,并且实际上发现这个方法非常简短而甜蜜
<link href="/styles/<?php echo mt_rand(1, 5); ?>.css" rel="stylesheet" type="text/css"/>
Run Code Online (Sandbox Code Playgroud)
在这里找到它,http://forum.mamboserver.com/showthread.php?t= 61029
非常感谢
附:A List Apart 还有一种非常简单而出色的方式来切换图像,http://www.alistapart.com/articles/randomizer/
归档时间: |
|
查看次数: |
6526 次 |
最近记录: |