基于css的页面中的Javascript随机图像生成器

Javascript random image generator in css-based page

本文关键字:图像 随机 css 基于 Javascript      更新时间:2023-09-26

正如标题所说,我正在尝试弄清楚如何在我的网页中调用这个javascript函数。 它适用于我的业务,模板只是一个基本的免费模板。 我敢肯定,对于比我更有经验的人,这可能只是正确格式化的简单问题。这是我正在使用的内容。

网页的 HEAD 部分中的代码:

var theImages = new Array() 
theImages[0] = 'splash1.jpg'
theImages[1] = 'splash2.jpg'
theImages[2] = 'splash3.jpg'
theImages[3] = 'splash4.jpg'
theImages[4] = 'splash5.jpg'
theImages[5] = 'splash6.jpg'
var j = 0
var p = theImages.length;
var preBuffer = new Array()
for (i = 0; i < p; i++){
  preBuffer[i] = new Image()
  preBuffer[i].src = theImages[i]
}
var whichImage = Math.round(Math.random()*(p-1));
function showImage(){
document.write('<img src="'+theImages[whichImage]+'">');
}
</script>

现在调用我使用的函数:

<SCRIPT LANGUAGE="JavaScript">
showImage();
</script>

这是我尝试实现它的页面:http://coloradopp.com/index4.html

我不只是显示图像,而是想调用该函数。 飞溅 1-6 的大小都与原始图像相同。

下面是代码片段:

<div id="splash">
<img class="pic" src="images/splash1.jpg" width="870" height="374" alt="" />
</div>

正如您可以告诉页面调用样式表(样式.css)的所有格式。

任何人都可以提供有关如何完成这项工作的任何提示吗? 从我收集到的信息来看,人们无法将javascript实现到css表中。 提前谢谢。

做这样的事情:

showImage() {
  var theImages = [ 'splash1.jpg', 'splash2.jpg', 'splash3.jpg', 'splash4.jpg', 'splash4.jpg' ];
  var img = theImages[Math.round(Math.random() * (theImages.length - 1))];
  document.getElementById('splash').innerHTML = '<img src="' + img + '">');
}

首先在函数中移动你的javascript代码,如下所示:

function showImage(){ ...your code goes here...}

然后,您可以在页面加载时启动该函数,如下所示:

<body onload="showImage()">

您可以将图像动态设置为背景图像并放置类似的东西

<script>
document.write('<style>#splash{ background-image:url(''images/splash'+Math.round(Math.random()*5+1)+'.jpg'');}</style>');
</script>

在页面的头部。使用此解决方案,您必须为div 标签 (870x374) 设置固定尺寸