最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Background-Image Slideshow in Js (& HTML, CSS) - Stack Overflow

programmeradmin3浏览0评论

I'm trying to implement a simple background image slideshow on my website but I can't find a good tutorial on the internet so I thought I'd ask here.

HTML:

<body>
   <h3>Wele!</h1>
   <p>Lorem ipsum dolor sit amet</p>
</body>

JS:

var i = 0;
var images = [];
var slideTime = 3000; // 3 seconds

images[0] = '/img/bg1.jpg';
images[1] = '/img/bg2.jpg';
images[2] = '/img/bg3.jpg';

function changePicture() {
    document.body.style.backgroundImage = images[i];

    if (i < images.length - 1) {
        i++;
    } else {
        i = 0;
    }

    setTimeout("changePicture()", slideTime);
}

window.onload = changePicture;

CSS:

body {
    background-image: url("img/bg2.jpg");
    background-position: center;
    background-size: cover;
}

I'm trying to implement a simple background image slideshow on my website but I can't find a good tutorial on the internet so I thought I'd ask here.

HTML:

<body>
   <h3>Wele!</h1>
   <p>Lorem ipsum dolor sit amet</p>
</body>

JS:

var i = 0;
var images = [];
var slideTime = 3000; // 3 seconds

images[0] = '/img/bg1.jpg';
images[1] = '/img/bg2.jpg';
images[2] = '/img/bg3.jpg';

function changePicture() {
    document.body.style.backgroundImage = images[i];

    if (i < images.length - 1) {
        i++;
    } else {
        i = 0;
    }

    setTimeout("changePicture()", slideTime);
}

window.onload = changePicture;

CSS:

body {
    background-image: url("img/bg2.jpg");
    background-position: center;
    background-size: cover;
}
Share Improve this question asked Jul 8, 2020 at 22:08 DavidDavid 751 gold badge2 silver badges10 bronze badges 1
  • 1 Is your code working? Is there a problem with it? – imvain2 Commented Jul 8, 2020 at 22:18
Add a ment  | 

1 Answer 1

Reset to default 4

Background image requires URL to wrap the image file when passing an image file.

var i = 0;
var images = [];
var slideTime = 3000; // 3 seconds

images[0] = 'https://via.placeholder./150/300AAA';
images[1] = 'https://via.placeholder./150/000300';
images[2] = 'https://via.placeholder./150/AAA300';

function changePicture() {
    document.body.style.backgroundImage = "url(" + images[i] + ")";

    if (i < images.length - 1) {
        i++;
    } else {
        i = 0;
    }
    setTimeout(changePicture, slideTime);
}

window.onload = changePicture;
body {
    background-image: url("https://via.placeholder./150/300AAA");
    background-position: center;
    background-size: cover;
}
<h3>Wele!</h3>
   <p>Lorem ipsum dolor sit amet</p>

发布评论

评论列表(0)

  1. 暂无评论