简体   繁体   English

自动幻灯片播放不起作用的JavaScript

[英]Automatic Slideshow Not Working JavaScript

I am currently trying to understand how to create a slideshow in JavaScript from W3Schools. 我目前正在尝试了解如何从W3Schools用JavaScript创建幻灯片。 The Manual slideshow worked perfectly but the automatic slideshow is not working in any way. 手动幻灯片完美运行,但自动幻灯片则无法正常运行。

HTML: HTML:

<!DOCTYPE html>

<html>

<head>
    <link rel="stylesheet" href="styles.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="scripts.js"></script>
</head>

<body>

    <div id="main_adverts">
        <img class="slide" src="images/imgslider1.jpg"/>
        <img class="slide" src="images/imgslider2.jpg"/>
        <img class="slide" src="images/imgslider3.jpg"/>
    </div>
</body>
<html>

JavaScript: JavaScript的:

var myIndex = 0;
carousel();

function carousel() {
    var i;
    var x = document.getElementsByClassName("slide");
    for (i = 0; i < x.length; i++) {
       x[i].style.display = "none";  
    }
    myIndex++;
    if (myIndex > x.length) {myIndex = 1}    
    x[myIndex-1].style.display = "block";  
    setTimeout(carousel, 2000); // Change image every 2 seconds
}

CSS: CSS:

#main_adverts{
    width: 70%;
    height: 70%;
    position: absolute;
    top: 20%;
    left: 15%;
    border: 1px solid black;
}

#main_adverts img{
    width: 100%;
    height: 100%;
    position: absolute;
}

For anyone who may come across this in the future. 对于将来可能遇到此问题的任何人。 The safest way to solve this issue is to wrap your code like the following: 解决此问题的最安全方法是将代码包装如下:

window.onload = function(){
    //Your code here
}

By doing so, regardless of where you place your JavaScript in the HTML file, it will wait to execute until the page has fully loaded. 这样,无论您将JavaScript放在HTML文件中的什么位置,它都将等待执行,直到页面完全加载为止。

Put the js link in last line inside the body tag: 将js链接放在body标签内的最后一行中:

<body>
    <!- rest of your html -->
    <script src="scripts.js"></script>
</body>

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

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