背景画像のある要素があります。その背景画像をランダムな画像 URL に変更することはできますか?
そのため、ユーザーがページを読み込むと、ランダムな背景画像が表示されます。
アップデート
私の質問に答えてくれた皆さん、ありがとうございます。
背景画像のある要素があります。その背景画像をランダムな画像 URL に変更することはできますか?
そのため、ユーザーがページを読み込むと、ランダムな背景画像が表示されます。
私の質問に答えてくれた皆さん、ありがとうございます。
はい。次に例を示します。
$(document).ready(function() {
$("body").css("background-image", "url("+your_random_image_url+")");
});
画像ファイルに「image1.jpg」「image2.jpg」などの名前を付けます。乱数を生成する
Math.floor(Math.random()*range_of_your_image_nums+1);
次に、この番号を使用して、ランダムな画像を次のようにロードします
$("#id_of_your_element").css("background","<url>");
これがそれを行うサンプルスクリプトです。以下は私が行う方法です。IE 6 および Firefox (2 および 3) でテスト済み。背景画像は右サイト固定でスクロールしません。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled</title>
<script type="text/javascript">
function changeImg(imgNumber) {
var myImages = ["images/image0.jpg", "images/image1.jpg", "images/image2.jpg", "images/image3.jpg"];
var imgShown = document.body.style.backgroundImage;
var newImgNumber =Math.floor(Math.random()*myImages.length);
document.body.style.backgroundImage = 'url('+myImages[newImgNumber]+')';
}
window.onload=changeImg;
</script>
<style type="text/css">
.bg {background-attachment:fixed; background-repeat: no-repeat; background-position:top right;}
</style>
</head>
<body class="bg">
<p>Some text</p>
<!-- put a lot text lines here to see that the background stays fixed. -->
<p>Some text</p>
</body>
</html>
すべての背景を含む配列を保持し、ランダムなものを$(document).ready()
$(document).ready(function() {
var backgrounds = ['link1', ..., 'linkN'];
$("#yourElementId").css("background-image: url("+backgrounds[Math.round(Math.random() * (backgrounds.length - 1))] +")");
});
$(document).ready(function() {
var images = ["the-nude-art.jpg", "the-secret-pic.jpg","topless-pic.png","oolala-pic.jpg"];
var rand_image = images[Math.floor(Math.random() * images.length)];
var my_site_image_folder_path = 'http://www.xyz.com/images/';
$('body').css('background-image', 'url("' + my_site_image_folder_path + rand_image + '")');
});
var backgrounds = ['',
'bg3.jpg',
'bg1.jpg',
'bg1013.jpg',
'bg123.gif',
'bg553.jpg',
'bg663.png',
'bgdaas3.jpg',
'bgdw3.jpg',
'bgdd3.jpg',
'dasd.png'
];
$('#elementID').css('background', 'url('+backgrounds[Math.random()*10]+')');