简体   繁体   English

更改页面刷新背景图片

[英]Change background image on page refresh

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。

PS 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. 如果有人知道如何改善我的php代码或可以提供有时导致代码失败的原因,则PS Solution不必是JavaScript,那将非常有帮助。

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. 那应该没问题。

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. 这样,您就可以继续使用正在使用的文件夹,而无需进行任何更改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM