duanhuau567787 2013-05-09 18:43
浏览 295
已采纳

使用jQuery和AJAX定期更改背景图像src

I'm trying to have the background image of the body of my page change every (approximatly) N seconds. For this i have a PHP function that echoes random image src when i call it using AJAX. I then replace the current body background image src by this newly generated one, but i can't get it to work.

Here is the code, is there anything wrong in it ?

(function($) {

    var $body = $('body');

    window.setInterval(function() {
        $.ajax({
            url: 'http://localhost/some_path/index.php?exec=getNewBkgImgSrc',
        }).done(function(data) {
            var newImage = new Image();
            newImage.onload = function() {
                $body.css('background-image', newImage.src);
            };
            newImage.src = data;
        });
    }, 5000);

})(window.jQuery);

And the PHP function which does work :

public function getNewBkgImgSrc() {
    echo CONTENT_URL_DIR.'/Wallpapers/wallpaper ('.rand(1, 20).').jpg';
}

Could this be because i'm using localhost ? I can mremeber having AJAX problems before when i was developping locally.

EDIT : A clue maybe is that the style property of the body element doesn't sseem to change / be set in Firebug. I also tried $('body').first() and $(document.body) and using url("") (in the value of background-image property) but it doesn't work either. The onload event does fire however.

Thanks for your help.

  • 写回答

3条回答 默认 最新

  • duan1226 2013-05-09 18:55
    关注

    Why are you creating a new image object if you are getting a URL back from PHP? Just set the background-image property of body to:

    $body.css('background-image', "url('" + data + "')");
    

    If using vanilla JS:

    document.body.style.backgroundImage="url('" + data + "')";
    

    See proper format for that property here: http://www.w3schools.com/cssref/pr_background-image.asp

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog