tableやtdの背景画像をランダムに表示する方法

[統計] HTMLからXHTMLへの移行を進めていますか?



0   名前: 古川 : 2005/06/21 05:27
はじめまして。
題名のとうりなんですが、テーブル等の背景画像を3種類ほど用意し、
更新するたびにランダムで入れ替わるようにしたいのですが宜しくお願い致します。

参考ページ
http://www.fujirockfestival.com/
のメニュー上の画像のランダム切り替えです。

宜しくお願いします。

1   名前: 通行人 : 2005/06/21 05:27
そのページはIISサーバですよね。

<style type="text/css">
#X {
background-repeat: no-repeat;
background-image: url("/image/background/xxx.gif");
}
</style>
...
<table id="X"> ... </table>

これの、「xxx.gif」の部分を動的にするのが簡単で確実です。

background-image: url("image/background/<%

var documentRoot = '/home/www/';
var relPath = 'image/background/';
var pattern = /\.gif$/i;

var file_name;
var gifs = [];
var allFiles = new Enumerator(
Server.CreateObject('Scripting.FileSystemObject')
.GetFolder( documentRoot + relPath )
.Files
);
for ( ; ! allFiles.atEnd(); allFiles.moveNext()) {
file_name = allFiles.item().Name;
if (pattern .test( file_name ))
gifs[ gifs.length ] = file_name;
}

Response.Write( gifs[ Math.floor( gifs.length * Math.random()) ] );

%>");


質問内容がクライアントでの処理だったとしても、
配列からランダムな要素を取り出す方法は同じですし、
フォルダの中身から *.gif のような条件でフィルターして
配列を自動的に作成する方法も同じです。

手軽に作るなら、

(function (selector) {
document.write(
'<style type="text/css">',
selector, ' {',
'background-repeat: no-repeat;',
'background-image: url("',
arguments[ 1 + Math.floor( (arguments.length - 1) * Math.random() ) ],
'");',
'}',
'<\/style>'
)
})(

'#X',// CSSのセレクタ

'/image/background/a.gif',
'/image/background/b.png',
'/image/background/c.jpg' // 最後はカンマを書かない

);


以上、何のテストもしていませんので動かなくても悪しからず。

一覧へ戻る