javascript 在页面刷新时更改背景图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19889287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:10:11  来源:igfitidea点击:

Change background image on page refresh

javascriptphpjqueryhtmlcss

提问by user2078845

I currently have some php that changes the background image of a div everytime the page is refreshed.

我目前有一些 php,每次刷新页面时都会更改 div 的背景图像。

In the head of my HTML I have this

在我的 HTML 的头部,我有这个

<?php 
$bg = rand(1, 6); 
$bgchange = $bg.".jpg"; 
?>

and then this

然后这个

<style type="text/css">
.cover {
  background-image: url('../img/backgrounds/<?php echo $bgchange; ?>');
}
</style>

As you can see this is a very simple bit of php it does do the job but I am having problems when the site is first loaded on a computer or if the internet is slow where the image fails to load.

正如您所看到的,这是一个非常简单的 php 代码,它确实可以完成这项工作,但是当网站首次加载到计算机上时,或者互联网速度很慢导致图像无法加载时,我遇到了问题。

Any javascript guys that can recommend a solution to this I would greatly appreciate, I'm also thinking javascript will be better as the image can 'fade' in etc. I am referencing jquery-1.10.2 in my project.

任何可以为此推荐解决方案的 javascript 人员,我将不胜感激,我也认为 javascript 会更好,因为图像可以“淡入”等。我在我的项目中引用了 jquery-1.10.2。

P.S. Solution does not have to be javascript if anyone knows how to improve my php code or can offer a reason why the code fails sometimes, that would be really helpful.

PS 解决方案不必是 javascript,如果有人知道如何改进我的 php 代码或者可以提供代码有时失败的原因,那将非常有帮助。

回答by Kevin Lynch

First create an array of images:

首先创建一个图像数组:

var images = ['image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg', 'image5.jpg'];

Then, set a random image as the background image:

然后,设置一个随机图片作为背景图片:

 $('body').css({'background-image': 'url(images/' + images[Math.floor(Math.random() *      images.length)] + ')'});

That should work no problem.

那应该没问题。

回答by Idan Magled

you can do (and should) do this action in js.

您可以(并且应该)在 js 中执行此操作。

on the document load function you can do this. //document load function

在文档加载功能上,您可以执行此操作。//文件加载函数

$(function(){

    var bgImage = (Math.floor(Math.random() * 6))+ ".jpg;"
    $('.cover').css('background-image',"../img/backgrounds/"+bgImage);
});

and this way you can keep using the folders you are using and not change anything.

这样您就可以继续使用您正在使用的文件夹,而不会更改任何内容。