使用Javascript / PHP在图像上设置时间间隔

时间:2013-08-07 10:20:23

标签: php javascript random time setinterval

我正在尝试使用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>
  ');

   ?>

提前致谢。

3 个答案:

答案 0 :(得分: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>

如果这有意义或者您有任何疑问,请告诉我们。)

答案 1 :(得分:0)

如果你想要一个完整的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秒后加载下一个随机图像。使用setTimeout优于setInterval,因为只有在加载上一张图像后才会调用超时。

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

答案 2 :(得分:0)

好的,我尝试了各种方法,但似乎无法让它无缝地工作。我现在已经开始工作,但是我对我实际需要的东西总是过分苛刻。

因此,以下代码使用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;
}

如果有人有更好的方法在页面加载时使用唯一链接显示随机图像并在特定时间间隔更改为随机图像,请告诉我:)我希望尽量减少这一切。

由于