更改背景图像 - javascript

2024-04-06

我想用 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 有一个简单的解决方法,这实际上也会使您的源代码变得不那么复杂。做身体relative,将每个单独的背景图像添加到bottom您的源代码(使它们在其他所有内容之后加载)位于命名包装器内。让我们一起去#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,以便我们的内容位于它们的前面,从而给人一种图像是背景图像的错觉。改变position:absolute to position:fixed如果你想要一个background-attachment:fixed影响。我假设您希望它们的宽度和高度是视口的宽度和高度;如果没有,请将它们更改为任何内容。我们将图像设置为display:none阻止他们all页面加载时加载。哎呀!

<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);

})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

更改背景图像 - javascript 的相关文章

随机推荐