admin管理员组文章数量:1323342
I currently have some php that changes the background image of a div everytime the page is refreshed.
In the head of my HTML I have this
<?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 puter or if the internet is slow where the image fails to load.
Any javascript guys that can remend 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.
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.
I currently have some php that changes the background image of a div everytime the page is refreshed.
In the head of my HTML I have this
<?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 puter or if the internet is slow where the image fails to load.
Any javascript guys that can remend 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.
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.
Share Improve this question edited Nov 10, 2013 at 11:53 Tobias 7,7711 gold badge29 silver badges44 bronze badges asked Nov 10, 2013 at 11:42 user2078845user2078845 6092 gold badges8 silver badges12 bronze badges2 Answers
Reset to default 3First 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.
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.
本文标签: javascriptChange background image on page refreshStack Overflow
版权声明:本文标题:javascript - Change background image on page refresh - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742135307a2422341.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论