代码之家  ›  专栏  ›  技术社区  ›  JamesHarrison

定期刷新页面上的图像

  •  3
  • JamesHarrison  · 技术社区  · 15 年前

    我正在构建一个页面来显示一堆网络摄像头图像,并定期更新它们,以便该页面可以用于一目了然的监视。但是,我有问题让定期重新加载工作。我的代码看起来像:

    <div class='cameras'> 
        <div class='camera'> 
          <h4>Desk</h4> 
          <img height='240' src='http://somehost/cameras/cam0/lastsnap.jpg' width='320'> 
        </div> 
        <div class='camera'> 
          <h4>Main Room</h4> 
          <img height='240' src='http://somehost/cameras/cam1/lastsnap.jpg' width='320'> 
        </div> 
        <div class='camera'> 
          <h4>Studio</h4> 
          <img height='240' src='http://somehost/cameras/cam2/lastsnap.jpg' width='320'> 
        </div> 
      </div> 
    

    理想情况下,我想让这些东西从他们指定的url每几秒钟重新加载一次,而不必为每个相机生成单独的JS。我已经将jQuery用于其他一些零碎的东西,所以坚持使用它会很好——然后,一个简单的JS解决方案也很好。

    有什么想法吗,斯塔克弗弗弗弗夫,诸神?

    4 回复  |  直到 15 年前
        1
  •  7
  •   JamesHarrison    15 年前

    好吧,解决了这个问题:

    function refreshCameras() {
      $('.camera img').attr('src', function(i, old) { return old.replace(/\?.+/,"?i=" + (Math.random()*1000)); });
      setTimeout(refreshCameras, 1000);
    }
    function refreshCamerasFirst() {
      $('.camera img').attr('src', function(i, old) { return old + "?i=" + (Math.random()*1000); });
      setTimeout(refreshCameras, 1000);
    }
    $(function() {
        setTimeout(refreshCamerasFirst, 1000);
    });
    

        2
  •  1
  •   Wazy    15 年前

    尝试将页面上的元标记重写为

    <meta http-equiv="Refresh" content="2; URL=yourpage.php">
    

    它对文本很酷

        3
  •  1
  •   zod    15 年前

    如果要在指定的持续时间内刷新页面,也可以在html中刷新

    将此标记添加到页眉标记

    <meta http-equiv="refresh" content="1">
    

    参考这个

    http://webdesign.about.com/od/metataglibraries/a/aa080300a.htm

        4
  •  1
  •   user372551 user372551    15 年前

    为图像生成图像源[以固定的时间间隔]

    var img = []; //just an image source. you can write your own code for image source
    
    img[0] ='http://site.com/pics/pic.jpg';
    img[1] ='http://site.com/pics/pic1.jpg';
    img[2] ='http://site.com/pics/pic2.jpg';
    img[3] ='http://site.com/pics/pic3.jpg';
    
    $(function() {
        $.each(img, function(i, val) {
            var images = new Image();
            images.src = val;    //preloading images for my example purpose
        });
        function reload() {
            $('img.alter').each(function() { //generate a url for  image source. 
                var src = img[Math.floor(Math.random() * img.length)];
                $(this).attr('src',src);
            });
        }   
        setInterval(reload , 5000)
    });
    

    Test it here