【问题标题】:Display random image when page loads without utilizing onload in the body tag页面加载时显示随机图像,而不使用 body 标签中的 onload
【发布时间】:2011-02-16 04:12:31
【问题描述】:

我正在尝试创建一段相当简单的 JavaScript,它在每次页面加载时显示来自数组的随机图像。我需要想出一种方法来让它运行而不向 body 标记添加代码。有没有办法在没有 onload 函数的情况下完成这个?

这是我依赖 onLoad 的内容:

    ImageSwitch=new Array();
    ImageSwitch[0]='1.jpg';
    ImageSwitch[1]='2.jpg';
    ImageSwitch[2]='3.jpg';
    ImageSwitch[3]='4.jpg';

    function swapImage() 
    {
        document.getElementById("theImage").setAttribute("src", ImageSwitch[

Math.round(Math.random()*3)])
    }

有任何替代想法来实现这一点吗?

【问题讨论】:

  • 请问你为什么不希望在 onload 函数中有这个?

标签: javascript image random


【解决方案1】:

您可以将其放在页面底部的 javascript 中,并设置一个超时时间。

setTimeout(swapImage, 500);或类似的东西。

【讨论】:

    【解决方案2】:

    只是不要把你的 javascript 放在一个函数中。

    如果你把它从函数中取出,它将在页面加载时运行。

    当它在函数中时,除非被调用,否则它不会运行。

    【讨论】:

    • 你必须小心这个。如果它位于错误的位置,则可以在元素(“theImage”)存在之前调用 javascript。这会导致错误。
    【解决方案3】:

    改编自 jQuery 的ready 函数,并对图像类型做了一些假设:

    (function() {
      var urls = ['1', '2', '3', '4'];
      function swap() {
        document.getElementById('theImage').setAttribute('src', urls[Math.round(Math.random() * urls.length)] + '.jpg');
      }
    
      // Mozilla, Opera and webkit nightlies currently support this event
      if ( document.addEventListener ) {
        window.addEventListener( 'load', swap, false );
      // If IE event model is used
      } else if ( document.attachEvent ) {
        window.attachEvent( 'onload', swap );
      }
    })();
    

    【讨论】:

      【解决方案4】:

      Wombleton 的回答是我会做的。但是,还有另一种方法可以做到这一点。在正文标记中,无论您要放置该随机图像的任何位置,都放置一个脚本,该脚本使用该图像的标记执行 document.write。确保您有一组图像 URL 和替换,如下所示:

      <html>
      <head>
      <title>Test</title>
      <script type="text/javascript">
        var imageURLs = [
             "http://www.myserver.com/images/image1.png"
           , "http://www.myserver.com/images/image2.png"
           , "http://www.myserver.com/images/image3.png"
        ];
        function getImageTag() {
          var img = '<img src=\"';
          var randomIndex = Math.floor(Math.random() * imageURLs.length);
          img += imageURLs[randomIndex];
          img += '\" alt=\"Some alt text\"/>';
          return img;
        }
      </script>
      </head>
      <body>
      <script type="text/javascript">
        document.write(getImageTag());
      </script>
      </body>
      </html>
      

      同样,这并不理想,但如果您不想使用任何类型的 onload 事件,而不仅仅是您放入 &lt;body&gt; 标记中的事件,这很有用。

      【讨论】:

        【解决方案5】:

        您可以只使用 document.write 来生成 img 标签。甚至像&lt;img src="javascript:Math.round(Math.random()*3)+'.jpg';" /&gt;

        【讨论】:

          【解决方案6】:

          您不需要在 body 标签中添加 onload - 在脚本中添加处理程序, 在头部,或者在正文之前加载的另一个脚本中。

          (function(){
            var fun=function(){
            // definefunction
            }
            if(window.addEventListener){
                window.addEventListener('load', fun,false);
                else if(window.attachEvent)window.attachEvent('load', fun);
           })();
          

          【讨论】:

            【解决方案7】:

            通过一些更改,此代码将随机加载图像并加载相应的链接。

            <!DOCTYPE html>
            <html>
            <head>
            <title>Jorgesys Html test</title>
            <script type="text/javascript">
              var imageUrls = [
                   "http://prueba.agenciareforma.com/appiphone/android/img/newspapers/stackoverflow.png"
                 , "http://ww.mydomain.com/img/newspapers/reforma.png"
                 , "http://ww.mydomain.com/img/newspapers/nytimes.png"
                 , "http://ww.mydomain.com/img/newspapers/oglobo.png"
                 , "http://ww.mydomain.com/img/newspapers/lefigaro.png"
                 , "http://ww.mydomain.com/img/newspapers/spiegel.png"
              ];
             var imageLinks = [
                   "http://www.stackoverflow.com"
                  , "http://www.reforma.com"
                   , "http://www.nytimes.com/"
                  , "https://oglobo.globo.com/"
                  , "http://www.lefigaro.fr/international/"
                 , "http://www.spiegel.de/international/"    
              ];
            
              function getImageHtmlCode() {
                var dataIndex = Math.floor(Math.random() * imageUrls.length);
                var img = '<a href=\"' + imageLinks[dataIndex] + '"><img src="';        
                img += imageUrls[dataIndex];
                img += '\" alt=\"Jorgesys Stackoverflow.com\"/></a>';
                return img;
              }
            </script>
            </head>
            <body bgcolor="white">
            <script type="text/javascript">
              document.write(getImageHtmlCode());
            </script>
            </body>
            </html>
            

            【讨论】:

              【解决方案8】:

              您的答案可以在glados.cc/myfaucet 找到。
              那里有一个脚本可供下载,其中包含您要查找的代码 这是一个简短的概要: 创建文件 config.php 并将其放入:

              <?php 
              // Advertisement Codes
              // All ads rotate. There are 3 types: square, text, and banner. Add HTML code to the array
              
              $squareAds = array('<iframe scrolling="no" style="border: 0; width: 250px; height: 250px;" src="http://myadserver.com"></iframe>');
              
              $textAds = array('<p><strong><a href="http://yoururl.com">YourURL</a></strong></p>', '<p><strong>Get your own site</strong> <a href="http://yoursite.com">here</a></p>');
              
              $bannerAds = array('<iframe scrolling="no" style="border: 0; width: 468px; height: 60px;" src="http://youradserver.com"></iframe>
              ');
              ?>
              

              然后,在您提供服务的页面上,例如 index.php 来显示您的随机链接或图像或文本:

              <?php
              require_once('config.php');
              function getAd($arr){
                  return $arr[rand(0, count($arr)-1)];
              }
              echo "any plain text or html" . getAd($textAds) . "any plain text or html" . getAd($bannerAds) . "any plain text or html" . getAd($squareAds) . "any plain text or html";
              ?>
              

              当然,您可以创建任意数量的 $xxxAds 数组并将它们命名为您想要的任何名称,并且您可以使用要显示的任何 html 或 jscript 填充数组,以及每个数组的无限数量,以 csv 格式 您还可以创建尽可能多的具有不同名称的新“getAd”函数,这样您就可以在一个页面上显示多个独特的 iframe 广告

              【讨论】:

                【解决方案9】:

                在数组中添加完整路径或目录路径的图像,刷新页面图像后添加正文标记,如&lt;body background="images/image1.jpg"&gt;

                <script type="text/javascript">
                function changeRandomimage() {
                    var imageArray = ["images/image1.jpg","images/image2.jpg","images/image3.jpg"];
                    var randomImage = Math.floor(Math.random() * imageArray.length);
                    document.body.background = imageArray[randomImage];
                }
                changeRandomimage();
                </script>
                

                【讨论】:

                  猜你喜欢
                  • 2017-02-20
                  • 2012-01-30
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 1970-01-01
                  • 2021-04-25
                  • 1970-01-01
                  相关资源
                  最近更新 更多