【问题标题】:Update background image with same URL periodically定期更新具有相同 URL 的背景图片
【发布时间】:2016-09-21 07:23:57
【问题描述】:

我正在开发一个 Angular JS 应用程序。我的身体背景必须根据我的服务器托管的图像每分钟改变一次。

在我的 HTML 中,我使用 ng-style 来设置背景图片:

<body ng-controller="mainCTRL" ng-style="{backgroundImage: 'url(' + imageURL + ')'}">

在我的 mainCTRL 中,imageURL 是这样设置的:

$scope.urlImage = serverURL + '/Images/background.png';

效果很好,但现在我需要刷新图像。托管图像每分钟更改一次,但始终托管在同一 URL 上。为此,我在我的 JS 代码中有这个:

startRefresh();

function startRefresh() {
    $interval(test, );
}

test = function () {
    $scope.urlImage = '';
    $timeout(function () { 
        $scope.urlImage = serverURL + '/Images/background.png'; 
    }, 1000);
};

计时器工作,每分钟调用一次测试函数,但图像始终相同。

我想要一个解决方案来更改图像,即使 URL 相同。

--

我是 javascript 初学者,对我的英语感到抱歉。谢谢

【问题讨论】:

  • 两个建议:确保服务器发送标头不缓存图像(至少不超过一分钟)并在图像 URL 后添加一个随机数作为请求参数以破坏浏览器的缓存,例如$scope.urlImage = serverURL + '/Images/background.png?r=' + Math.random();

标签: javascript html angularjs background-image ng-style


【解决方案1】:

尝试将网址更改为:

var currentTime = new Date().getTime();
$scope.urlImage = serverURL + '/Images/background.png?' + currentTime;

【讨论】:

  • 谢谢!它工作得很好 =) 我在 3 分钟内验证了你的答案;)
【解决方案2】:

在您的测试函数中尝试此更改:

test = function () {
    $scope.urlImage = '';
    $timeout(function () { 
        $scope.urlImage = ''; // add this line
        $scope.urlImage = serverURL + '/Images/background.png'; 
    }, 1000);
};

希望这对你有用.. :)

【讨论】:

  • 我试过了,它不起作用,因为第二次更改后urlImage是一样的。
猜你喜欢
  • 2020-06-29
  • 1970-01-01
  • 2019-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多