改变背景图像 – JavaScript
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了改变背景图像 – JavaScript,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2665字,纯文字阅读大概需要4分钟。
内容图文
![改变背景图像 – JavaScript](/upload/InfoBanner/zyjiaocheng/699/40aa658da3504596a60188564e7e041b.jpg)
我想用JavaScript更改背景图片.
JS:
<head>
<script type="text/javascript">
// Ta funkcja odpowiedzialna jest odpowiedzialna za zmiane obrazow w tle
$(window).load(function(){
var i = 0;
var images = ['images/1.jpg','images/2.jpg','images/3.jpg','images/4.jpg','images/5.jpg'];
var image = $('#slideit');
image.css('background-image', 'url(images/1.jpg)');
image.css('background-size', 'cover');
setInterval(function(){
image.css('background-image', 'url(' + images [i++] +')');
// image.fadeOut(1500, function (){
// image.fadeIn(1000);
// })
if(i == images.length) i = 0;
}, 6000);
});
</script>
</head>
HTML:
<body id="slideit" style="width:100%;height:100%;">
问题在于使图像平滑变化.注释掉的代码使网站中的所有内容都淡入淡出,除了背景外淡出.为什么会这样?此代码有效,但不能平滑地更改图像.如何淡入淡出图像?
解决方法:
不幸的是,CSS不支持背景图像的动画(通过转换).为什么?实际上,我不确定为什么.但这足以让他们知道他们没有. Javascript通过扩展CSS功能直接工作.简而言之,如果不编写设计用于破解其功能的非常复杂的代码,则无法使用Javascript完成您想要做的事情.
然而,使用jQuery有一个简单的方法,它实际上会使你的源代码变得更简单.使主体相对,将每个单独的背景图像添加到源的底部(以便在其他所有内容之后加载它们)在命名包装器中.让我们一起去#backgrounds吧.
<style>
body{
height:100%;
position:relative
}
#backgrounds img{
position:absolute;
z-index:1; // this is important
top:0;
left:0;
width:100%;
height:100%;
opacity:0;
display:none;
}
#wrapper{
position:relative;
z-index:3; // again, this is important
}
</style>
我们将包装器的z-index设置为高于图像的z-index,使得我们的内容位于它们的前面,从而给出了图像是背景图像的错觉.更改位置:绝对位置:固定,如果您想要背景附件:固定效果.我假设你想要它们的宽度和高度是视口的宽度和高度;如果不是,就把它们改成什么.我们将图像设置为display:none,以便在页面加载时阻止它们全部加载.呸!
<div id="wrapper">
all of your page are belong to us...
</div>
<div id="backgrounds">
<img src="background/one.jpg" alt="">
<img src="background/two.jpg" alt="">
<img src="background/three.jpg" alt="">
</div>
然后使用基于图像数量的计数器简单地遍历每个图像(这样您可以轻松地在以后轻松剪切和粘贴更多图像):
$(function(){
var total = $('#backgrounds img').length;
var counter = 1;
function cycle(){
// Makes old backgrounds appear beneath new ones
$('#backgrounds img').css('z-index','1')
// Set it to display and opacity 0 so we get the effect
$('#backgrounds img:nth-child('+counter+')').css({'opacity':'0','display':'block','z-index':'2'})
// Fade the background in
$('#backgrounds img:nth-child('+counter+')').animate({'opacity':'1'},1500)
// increase the counter
counter++
// make sure we're working within the quantity of images we have
if( counter > total ){ counter = 1 }
}
cycle();
setInterval(function(){cycle()},6000);
})
内容总结
以上是互联网集市为您收集整理的改变背景图像 – JavaScript全部内容,希望文章能够帮你解决改变背景图像 – JavaScript所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。