1 回答
TA贡献1831条经验 获得超10个赞
至少,看起来有一个问题是:
您的 HTML 中有一个带有 ID 的图像元素
diapo
,然后在 DOM 中,它有一个空src
属性。在中,您尝试使用存储在变量中的空属性来创建名为
slide.js
的类的新实例。Diaporama
diaporama
src
src
slide.js
由于
img
元素需要具有src
实际 URL 的属性,为了在该 URL 处显示图像,您什么也看不到,因为您没有提供 URL(您也不会收到错误,因为空src
属性是完全有效的) HTML,并且不会导致 JS 错误)
针对评论的更新
关键问题(或疏忽)是您:
index.html 文件中的轮播元素,然后在 DOM 中表示(这正是我们所期望的)
Diaporama
一个名为diaporama
in的类的实例slide.js
,它没有指向您希望它具有的DOM 轮播的链接diaporama
:所有内容都是 aString
,取自src
DOM 轮播的属性,它引用各种图像的 URL 路径。根据您编写的代码,实例diaporama
永远无法“伸出援手”并更新 DOM 轮播。
值得庆幸的是,修复非常简单。
如您所知,DOM 和您创建的对象之间需要存在链接;创建这样的链接非常简单,只涉及 DOM 查询。
我添加了一个解决方案(我已将所有 JS 放在一个文件中,而不是像您那样放在两个文件中 - 但这并不重要)
class Diaporama {
constructor(imgElem, images) {
this.imgElem = imgElem;
this.images = images;
this.position = 0;
this.start();
}
slideLeft() {
if (this.position <= 0) {
this.position = this.images.length - 1;
} else {
this.position--;
}
// this is part of the 'bridge' between "carousel.js" and the DOM
this.imgElem.src = this.images[this.position];
}
slideRight() {
// there was an error in your original "slideRight" method: a typo and an "off-by-error"
if (this.position >= this.images.length-1) {
this.position = 0;
}
else {
this.position++;
}
// this is part of the 'bridge' between "carousel.js" and the DOM
this.imgElem.src = this.images[this.position];
}
start() {
// this is part of the 'bridge' between "carousel.js" and the DOM
this.imgElem.src = this.images[this.position];
}
}
// prefer an Array literal rather than call to Array -- less verbose, and slightly faster
var images = ['img/one.jpg', 'img/two.jpg', 'img/three.jpg'];
// This is where 'bridge' between "carousel.js" and the DOM is created: we 'cache' a reference to the carousel 'img' element,
// which we will then modify from within the 'carousel' instance of class Diaporama
var imgElem = window.document.getElementById('carousel').querySelector('img');
var carousel = new Diaporama(imgElem, images);
carousel.start();
// create 'delegated' event listener on document, and trigger correct method of 'carousel' in response to user interaction
window.document.addEventListener('click', ev => {
const target = ev.target;
if(target.id === 'back_button') {
carousel.slideLeft();
} else if(target.id === 'next_button') {
carousel.slideRight();
}
});
.carousel {
max-height: 400px;
max-width: 600px;
background: rgb(250,250,200);
overflow: hidden;
}
.button-wrapper {
display: flex;
justify-content: space-around;
}
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Carousel</title>
</head>
<body>
<h1>Carousel slider (OOP)</h1>
<section id="carousel" class="carousel">
<div class="button-wrapper">
<button id="back_button">Back</button>
<button id="next_button">Next</button>
</div>
<img src="" alt="carousel image">
</section>
<script src="carousel.js"></script>
</body>
</html>
我希望这有助于回答您的问题!
添加回答
举报