gpt4 book ai didi

javascript 程序在 codepen 中有效,但在我尝试过的任何浏览器中都无效

转载 作者:太空宇宙 更新时间:2023-11-03 22:46:48 24 4
gpt4 key购买 nike

我迷失了自己做错了什么,我发现这段代码在 codepen 中运行良好正如我所说,但每当我尝试在 atom 或 chrome 中使用它时,关于 className 标签的错误不断弹出,非常困惑。

    var slides = document.querySelectorAll('#slides .slide');
var currentSlide = 0;
var slideInterval = setInterval(nextSlide, 10000);

function nextSlide() {
slides[currentSlide].className = 'slide';
currentSlide = (currentSlide + 1) % slides.length;
slides[currentSlide].className = 'slide showing';
}
/*
essential styles:
these make the slideshow work
*/

#slides {
position: relative;
height: 150px;
padding: 0px;
margin: 0px;
list-style-type: none;
}
.slide {
position: absolute;
left: 0px;
top: 0px;
width: 100%;
height: 100%;
opacity: 0;
z-index: 1;
-webkit-transition: opacity 1s;
-moz-transition: opacity 1s;
-o-transition: opacity 1s;
transition: opacity 1s;
}
.showing {
opacity: 1;
z-index: 2;
}
/*
non-essential styles:
just for appearance; change whatever you want
*/

.slide {
font-size: 40px;
padding: 40px;
box-sizing: border-box;
background: #333;
color: #fff;
}
.slide:nth-of-type(1) {
background: red;
}
.slide:nth-of-type(2) {
background: orange;
}
.slide:nth-of-type(3) {
background: green;
}
.slide:nth-of-type(4) {
background: blue;
}
.slide:nth-of-type(5) {
background: purple;
}
<ul id="slides">
<li class="slide showing">Slide 1</li>
<li class="slide">Slide 2</li>
<li class="slide">Slide 3</li>
<li class="slide">Slide 4</li>
<li class="slide">Slide 5</li>
</ul>

最佳答案

那是因为CodePen ,以及 JSFiddle可能还有大多数其他在线编码工具,默认情况下将 JS 代码包装在 document.ready 中或 window.load 事件处理程序(或将 <script> 放在 <body> 中其他元素之后)。

在 JSFiddle 上,您可以在 JS 面板中将其关闭,但在 CodePen 上我还没有找到这样做的方法: enter image description here

  • “onLoad”是 window.onload
  • “onDomready”是 document.ready

在您自己的服务器(或本地计算机)上,如果您的脚本在(链接)<head>而且您没有明确地将其包装在 window.load 中或 document.ready ,您的 JS 代码将在页面上加载 HTML 元素之前执行。
所以你得到了错误,因为代码试图设置 className尚不存在的东西:

uncaught typing error, can not set property "className" of undefined

如果您使用的是纯/ Vanilla JS,我会选择 window.load ,正如您从上面的链接中看到的那样,document.ready没有得到广泛支持。这就是你如何使用 window.load :

window.onload = function() {
/*your code*/
};

关于javascript 程序在 codepen 中有效,但在我尝试过的任何浏览器中都无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41581933/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com