【问题标题】:Javascript random image generator in css-based page基于 css 的页面中的 Javascript 随机图像生成器
【发布时间】:2012-05-13 15:57:12
【问题描述】:

正如标题所说,我正在尝试弄清楚如何在我的网页中调用这个 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

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

这里是sn-p的代码:

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

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

任何人都可以提供有关如何进行这项工作的任何提示吗?根据我收集的信息,无法将 javascript 实现到 css 表中。提前致谢。

【问题讨论】:

    标签: javascript html css image random


    【解决方案1】:

    做这样的事情:

    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 + '">');
    }
    

    【讨论】:

      【解决方案2】:

      首先将您的 javascript 代码移动到函数中,例如:

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

      然后您可以像这样在页面加载时启动该功能:

      <body onload="showImage()">
      

      【讨论】:

        【解决方案3】:

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

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

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

        【讨论】:

        • 谢谢,这实际上很有帮助。唯一的问题是,由于它将图像作为背景,它们最终占据的空间比图片大。有没有办法解决这个问题?我不能只调用一个函数作为图像源吗?
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-04-25
        • 1970-01-01
        • 1970-01-01
        • 2023-02-01
        • 1970-01-01
        • 2021-11-21
        • 2012-03-13
        相关资源
        最近更新 更多