每5秒重新加载背景图片

Reload background pic every 5 secs

本文关键字:加载 背景图片 5秒 新加载      更新时间:2023-09-26

我需要重新加载背景图片每5秒从一个php文件拉img-url。像这样:

PHP(我知道如何做PHP部分):

<?
//mysql connection
//mysql query
echo ('$picurl')
?>
HTML:

<td height="282" style= "background:url(img/frontpage/johana.jpg) no-repeat">
<-- html content -->
</td> 

未经测试,但应该可以做到(使用JQuery):

   setInterval(fetchImage(), 5000);
    function fetchImage() {
        $.get("/path/to/your.php", function(data){ // "data" is whatever your php script returns
            //console.log(data); // for debugging your php response
            var imageString = 'url(' + data + ') no-repeat'; // Build your background css string
            $('td#yourID').css('background',imageString); // assign the value of imageString to the td's background css property
        });
    }

你的php文件必须返回一个单独的图像路径

希望有帮助:编辑:试试这个:D

<script>
        var slideShowNum = 0;
        var slideShowSources = ["<? echo ('$picurl') ?>", "<? echo ('$picur2') ?>", "<? echo ('$picur3') ?>", "<? echo ('$picur4') ?>"];
        function SlideShowImageChanger() {
            slideShowNum++;
            if (slideShowNum == 4) {
                slideShowNum = 0;
            }
            var imageSrc = slideShowSources[slideShowNum];

            var imageElm = document.getElementById('YourTdId');
            imageElm.style.backgroundImage = "url(" + imageSrc + ")";
        }
</script>

<td height="282" id="YourTdId" style= "background:url(img/frontpage/johana.jpg) no-repeat">
<-- html content -->
</td> 
<script>
setInterval(SlideShowImageChanger, 8000);
</script>

为TD指定一个ID或类别,然后像这样的事情将使您继续前进:

setInterval(function() {
    $.ajax({
        url: 'path/to/server/script.php',
        success: function(response) {
            // This assumes the output of your server script is simply
            // an image url
            $('#td-id').css('background-image', response);
        }
    });
}, 5000);

您使用的jquery:

setInterval(function() {
      // Do something every 2 seconds
}, 2000);
对php页面执行异步HTTP (Ajax)请求并使用结果使用http://api.jquery.com/css/设置页面的CSS