【问题标题】:Set time intervals on images with Javascript/PHP使用 Javascript/PHP 设置图像的时间间隔
【发布时间】:2013-08-08 16:16:09
【问题描述】:

我正在尝试使用 Javascript 为已在使用 PHP 加载页面时随机选取的图像设置时间间隔。显然我无法使用 PHP 设置时间间隔。所以图像是使用 PHP 随机选择的,但是一旦它被随机选择并加载了页面,我希望 Javascript 接管并以 20 秒的时间间隔生成一个新的随机选择的图像。

我可能会放弃整个 PHP 想法并完全使用 Javascript,但我现在很想看看我是否可以让它工作。

下面是我的 PHP 代码:

    <?php

 $img_rand = array(
  1 => array(
     'url' => 'www.tautic.com/', 
    'img' => '1.jpg', 
    'wth' => '472',        
    'hgt' => '100',      
  'ttl' => 'Tautic',    
    'alt' => 'Tautic'  
   ),                              
   2 => array(
     'url' => 'www.designspark.com/', 
    'img' => '2.jpg', 
    'wth' => '472',        
    'hgt' => '100',        
  'ttl' => 'Design Spark',    
    'alt' => 'Design Spark'  
  ),
  3 => array(
     'url' => 'www.involutionstudios.net/',
    'img' => '3.jpg',
    'wth' => '472',        
    'hgt' => '100',        
  'ttl' => 'Involution Studios - Web Design',   
    'alt' => 'Involution Studios - Web Design'  
   ),
    4 => array(
     'url' => 'www.explorestem.co.uk/', 
    'img' => '4.jpg', 
    'wth' => '472',     
    'hgt' => '100',        
  'ttl' => 'Explore Stem',    
    'alt' => 'Explore Stem' 

   ),
   ); 

   $img = array_rand($img_rand); 
   echo('      
   <div class="random-img">    
   <a href="http://'.$img_rand[$img]['url'].'" title="'.$img_rand[$img]['ttl'].'"                  
   target="_blank">
    <img src="sponsorimg/'.$img_rand[$img]['img'].'" width="'.$img_rand[$img]['wth'].'"          
   height="'.$img_rand[$img]['hgt'].'" alt="'.$img_rand[$img]['alt'].'" /> 
  </a>
  </div>
  ');

   ?>

提前致谢。

【问题讨论】:

    标签: php javascript random time setinterval


    【解决方案1】:

    在 PHP 中使用数组的问题是只有 PHP 可以访问它,即 JavaScript 不知道要加载什么 url。因此,如果您打算保留 php,请使用下面的选项 1,否则废弃 php 并使用选项 2:

    选项 1

    您必须在主视图上使用 ajax,并保持 php 独立。在php页面上,不输出图片,而是将图片信息输出为JSON对象,例如

    $img = array_rand($img_rand);
    header('Content-type: application/json');
    echo json_encode($img);
    

    然后在显示所有内容的页面上,使用 javascript(我使用 jQuery,因为它使 ajax 更容易)来加载图像:

    <div class="random-img"></div>
    <script type="text/javascript>
    imgLoop = function() {
        $.get('randomimage.php', function(img) {
            var el = '<a href="http://'+img.url+'" title="'+img.ttl+'" target="_blank">';
            el += '<img src="sponsorimg/'+img.img+'" width="'+img.wth+'" height="'+img.hgt+'" alt="'+img.alt+'" /></a>';
            $('.random-img').empty().append(el);
        });
    };
    setInterval(imgLoop, 20000);
    </script>
    

    选项 2(更好的 imo)

    除非你试图阻止你的用户在他们试图查看你的源代码时看到图像数组,否则选项 1 中完全不需要 ajax/php。你可以完全废弃 php 并将你的图像存储为对象数组,例如

    images = [
        {
            'url': 'www.tautic.com/', 
            'img': '1.jpg', 
            'wth': '472',        
            'hgt': '100',      
            'ttl': 'Tautic',    
            'alt': 'Tautic'
        },
        {
            'url': 'www.designspark.com/', 
            'img': '2.jpg', 
            'wth':'472',        
            'hgt':'100',        
            'ttl':'Design Spark',    
            'alt':'Design Spark'
        }
        //And so on..
    ];
    

    然后对于间隔,只需使用:

    <div class="random-img"></div>
    <script type="text/javascript>
    imgLoop = function() {
        var img = images[Math.floor(Math.random() * images.length)];
        var el = '<a href="http://'+img.url+'" title="'+img.ttl+'" target="_blank">';
        el += '<img src="sponsorimg/'+img.img+'" width="'+img.wth+'" height="'+img.hgt+'" alt="'+img.alt+'" /></a>';
        $('.random-img').empty().append(el);
    };
    setInterval(imgLoop, 20000);
    </script>
    

    让我知道这是否有意义或者如果您有任何问题:)

    【讨论】:

    • 感谢您提供如此详细的答案,我将使用选项 2 :) 我了解选项 2 中代码的第二个 sn-p,但顶部的 sn-p(图像数组)在哪里我把那个?谢谢:)
    • 顶部基本上可以放在&lt;script&gt; 标签内的任何地方。让我知道它是否有效.. :)
    • 似乎无法正常工作,我无法将我在这里所做的事情发布太久。这个网站有私信吗?我也尝试了 Ajax 的想法,但没有结果:( 没有图像出现,但也没有错误。
    • 无论如何你可以通过做一个 jsFiddle 来帮助我吗?或者给我发电子邮件 liam@invoweb .net,我很确定你的回答会奏效,只是有些地方不太对劲。谢谢
    • 感谢您抽出宝贵时间来做这件事 :) 一切看起来都很棒,在图像更改之间做一个淡入淡出效果有多难?干杯。
    【解决方案2】:

    如果您想要一个完整的 javascript 解决方案,那么您必须将数组保留在客户端上。

    将 HTML / PHP 文件中的动态字段保留为空白并从 javascript 加载它们。

    <div class="random-img">
        <a target='_blank' title='' href='' >
            <img id='imageToLoad' src='' height='' width='' alt='' />
        </a>
    </div>
    

    我已经为事件绑定添加了 JQuery,但如果需要,可以将其更改为纯 javascript。

    这里监控图像的加载事件。加载或错误事件超时 20 秒后加载下一个随机图像。使用setTimeoutsetInterval 更有优势,因为只有在加载前一个图像后才会调用超时。

    loadImage 函数被显式调用一次以首次加载图像。

    $(document).ready(function () {
        $('#imageToLoad').on('load', function(e){
           var imageElem = this;
            setTimeout(function(){
                loadImage(imageElem);
            }, 20 * 1000);
        }).on('error',function(e){
           var imageElem = this;
            setTimeout(function(){
                loadImage(imageElem);
            }, 20 * 1000);
        });
    
        function loadImage(imageElem){
            imageElem = imageElem || $('#imageToLoad').get(0);
            var rndImage = imageArr[Math.floor(Math.random() * imageArr.length)];
            imageElem.src = rndImage.img;
            imageElem.height = rndImage.hgt;
            imageElem.width = rndImage.wth;
            imageElem.alt = rndImage.alt;
            imageElem.parentNode.href = rndImage.url;
            imageElem.parentNode.title = rndImage.ttl;
        }
    
        var imageArr = [{
            'url' : 'www.tautic.com/', 
            'img' : '1.jpg', 
            'wth' : '472',        
            'hgt' : '100',      
            'ttl' : 'Tautic',    
            'alt' : 'Tautic'
        },{
            'url' : 'www.designspark.com/', 
            'img' : '2.jpg', 
            'wth' : '472',        
            'hgt' : '100',        
            'ttl' : 'Design Spark',    
            'alt' : 'Design Spark'
        },{
            'url' : 'www.involutionstudios.net/',
            'img' : '3.jpg',
            'wth' : '472',        
            'hgt' : '100',        
            'ttl' : 'Involution Studios - Web Design',   
            'alt' : 'Involution Studios - Web Design'
        },{
            'url' : 'www.explorestem.co.uk/', 
            'img' : '4.jpg', 
            'wth' : '472',     
            'hgt' : '100',        
            'ttl' : 'Explore Stem',    
            'alt' : 'Explore Stem'
        }];
    
        loadImage();
    });
    

    Working Example

    【讨论】:

    • 感谢您的详细解答。这与我拥有的其他一些 .js 冲突,但我不知道为什么。 involutionstudios.net/earthrover/js/social.js ...您的脚本也在 20 秒后更改社交选项卡上的图像。嗯。谢谢
    • 您可以使用$('#imageToLoad').on('load'... 而不是$('img').on('load'...,因此它只会绑定到该特定图像元素。
    • 我将您新编辑的代码合并到我的网站中,它可以工作,但有时图像不会改变,或者它会进行 5/6 次更改而没有问题然后停止。我还检查了您的 jsFiddle 并遇到了同样的问题。奇怪:|谢谢。
    【解决方案3】:

    好的,我尝试了各种方法,但似乎无法让它无缝工作。我现在可以使用它了,但是对于我真正需要的东西,我期望它完全是矫枉过正。

    所以下面的代码使用 PHP 在页面加载时选择一个随机图像,然后使用 jQuery/Javascript/CSS 以 5s 间隔随机显示另一个图像,并且所有图像都可以链接等。

    PHP -

    <?php
    
    $img_rand = array(
       1 => array(
             'url' => 'www.tautic.com/', 
            'img' => '1.jpg', 
            'wth' => '472',        
            'hgt' => '100',      
          'ttl' => 'Tautic',    
            'alt' => 'Tautic'  
    ),                              
       2 => array(
             'url' => 'www.designspark.com/', 
            'img' => '2.jpg', 
            'wth' => '472',        
            'hgt' => '100',        
          'ttl' => 'Design Spark',    
            'alt' => 'Design Spark'  
    ),
       3 => array(
             'url' => 'www.involutionstudios.net/',
            'img' => '3.jpg',
            'wth' => '472',        
            'hgt' => '100',        
          'ttl' => 'Involution Studios - Web Design',   
            'alt' => 'Involution Studios - Web Design'  
    ),
       4 => array(
             'url' => 'www.explorestem.co.uk/', 
            'img' => '4.jpg', 
            'wth' => '472',     
            'hgt' => '100',        
          'ttl' => 'Explore Stem',    
            'alt' => 'Explore Stem' 
    
    ),
    ); 
    
    $img = array_rand($img_rand); 
    echo('
    
       <a href="http://'.$img_rand[$img]['url'].'" title="'.$img_rand[$img]['ttl'].'" target="_blank">
        <img src="sponsorimg/'.$img_rand[$img]['img'].'" width="'.$img_rand[$img]['wth'].'" height="'.$img_rand[$img]['hgt'].'" alt="'.$img_rand[$img]['alt'].'" /> 
       </a>
    
    ');
    
    ?>
    

    Javascript

    <script type="text/javascript">
    
    
    
    function slideSwitch() {
        var $active = $('#slideshow DIV.active');
    
        if ( $active.length == 0 ) $active = $('#slideshow DIV:last');
    
    
         var $sibs  = $active.siblings();
         var rndNum = Math.floor(Math.random() * $sibs.length );
         var $next  = $( $sibs[ rndNum ] );
    
    
        $active.addClass('last-active');
    
        $next.css({opacity: 0.0})
            .addClass('active')
            .animate({opacity: 1.0}, 1000, function() {
                $active.removeClass('active last-active');
            });
    }
    
    $(function() {
        setInterval( "slideSwitch()", 5000 );
    });
    
    </script>
    

    HTML

    <div class="random-img">
    <div id="slideshow"> 
    
    
    
        <div class="active">
        <?php require($INC_DIR. "rah.php");?>
        </div>
        <div>
       <a href="http://www.tautic.com/" title="Tautic" target="_blank">
        <img src="sponsorimg/1.jpg" width="472" height="100" alt="Tautic" /> 
       </a>
    
        </div>
        <div>
       <a href="http://www.designspark.com/" title="Design Spark" target="_blank">
        <img src="sponsorimg/2.jpg" width="472" height="100" alt="Design Spark" /> 
       </a>
        </div>
        <div>
          <a href="http://www.involutionstudios.net/" title="Involution Studios - Web Design" target="_blank">
        <img src="sponsorimg/3.jpg" width="472" height="100" alt="Involution Studios - Web Design" /> 
       </a>
    
        </div>
        <div>
        <a href="http://www.explorestem.co.uk/" title="Explore Stem" target="_blank">
        <img src="sponsorimg/4.jpg" width="472" height="100" alt="Explore Stem" /> 
       </a>
    
        </div>
    
    </div>
    </div>
    

    最后是 CSS

    .random-img 
    {
    position: fixed ;
    bottom:15px;
    z-index:20;
    width:470px;
    height:100px;
    right:2%;
    overflow:hidden;
    border:5px solid white;
    border-radius:10px;
    
    
    }
    
    
    #slideshow {
        position:relative;
        height:350px;
    }
    
    #slideshow DIV {
        position:absolute;
        top:0;
        left:0;
        z-index:8;
    }
    
    #slideshow DIV.active {
        z-index:30;
    }
    
    #slideshow DIV.last-active {
        z-index:25;
    }
    

    如果有人有更好的方法在页面加载时显示带有唯一链接的随机图像并在特定时间间隔更改为随机图像,请告诉我 :) 我希望将其最小化。

    谢谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-20
      • 2011-05-23
      • 2020-06-21
      • 2022-01-23
      • 1970-01-01
      • 2014-04-04
      • 2021-07-22
      • 1970-01-01
      相关资源
      最近更新 更多