我想用两个按钮更改DIV的内容。寻找纯javaScript解决方案。另外,我想有一个自动播放功能,该功能每2秒更改一次内容。单击其中一个按钮时,自动播放功能应停止。
现在,我设法用“可怜的”代码做到了这一点,并且没有自动播放功能。也许这里有人知道更好的方法?
change = document.getElementById("change");
button2 = document.getElementById("button2");
button2.addEventListener("click", function() {
change.style.background = "orange";
button1.style.background = "orange";
button2.style.background = "black";
});
button1 = document.getElementById("button1");
button1.addEventListener("click", function() {
change.style.background = "black";
button1.style.background = "black";
button2.style.background = "orange";
});
#change {
width: 300px;
height: 100px;
background: rgba(0, 0, 0, 1);
}
#button1,
#button2 {
color: grey;
display: block;
}
<div id="change"></div>
<button id="button1">Button 1</div>
<button id="button2">Button 2</div>
最佳答案
因此,似乎您想要某种轮播。
下面的以下示例使您可以浏览内容,也可以自动进行。
您的视图应以数组/列表数据类型保存。
最后,我将使用类而不是id。这使代码更具可扩展性。如果需要,可以稍后对其进行修改以创建插件。
const views = [{
content : '<h1>View #1</h1>',
style : { backgroundColor : 'orange', color : 'black' }
}, {
content : '<h1>View #2</h1>',
style : { backgroundColor : 'black', color : 'orange' }
}, {
content : '<h1>View #3</h1>',
style : { backgroundColor : 'red', color : 'white' }
}];
var timerId = null;
var currentView = 0;
window.addEventListener('DOMContentLoaded', onReady);
function onReady() {
let ct = document.querySelector('.container');
ct.querySelector('.btn-prev').addEventListener('click', handlePrevClick);
ct.querySelector('.btn-next').addEventListener('click', handleNextClick);
ct.querySelector('.btn-auto').addEventListener('click', handleAutoClick);
initializeView();
}
function handlePrevClick() {
currentView = (currentView + views.length - 1) % views.length;
initializeView();
}
function handleNextClick() {
currentView = (currentView + 1) % views.length;
initializeView();
}
function handleAutoClick(e) {
if (timerId == null) {
e.target.innerHTML = 'Stop';
timerId = setInterval(() => {
handleNextClick();
}, 1000);
} else {
e.target.innerHTML = 'Auto';
clearInterval(timerId);
timerId = null;
}
}
function initializeView() {
let container = document.querySelector('.container');
let viewport = container.querySelector('.viewport');
let view = views[currentView];
viewport.innerHTML = view.content;
//viewport.style.backgroundColor = view.style.backgroundColor;
//viewport.style.color = view.style.color;
Object.assign(viewport.style, view.style);
}
.container {
width: 300px;
}
.viewport {
width: 100%;
height: 100px;
border: thin solid grey;
}
.btn-container {
width: 100%;
text-align: center;
margin-top: 0.5em;
}
.btn-container button {
margin: auto 0.25em;
}
<div class="container">
<div class="viewport"></div>
<div class="btn-container">
<button class="btn-prev">Prev</button>
<button class="btn-auto">Auto</button>
<button class="btn-next">Next</button>
</div>
</div>