大家下午好。
我是 JavaScript 方面的新手,一般来说是编码方面的新手。我想创建一个“简单”的应用程序来在一组文本中来回移动。以我的一点知识,我可以到达这里,但没有成功。任何帮助将不胜感激。
document.getElementById("botonatras").addEventListener("click", next);
function next () {
var array = ["text1", "text2", "text3"];
var currentText = 0;
var textMax = 3;
currentText = (currentText + 1) %textMax;
document.getElementById("demo").innerHTML = currentText;
}
.demo {
height: 200px;
width:300px;
background-color:lightblue;
font-family:tahoma;
text-align:center;
font-size:18px;
}
.boton{
width:200px;
height:50px;
border:solid;
border-radius:5px;
background-color: rgba(255,90,18,0.5);
border-color:red;
color:white;
}
<html>
<body>
<p>Aplicacion para realizar lecturas de aplicacion.</p>
<button id="botonatras" class ="boton">Atras</button>
<button id="myBtn" class ="boton">Adelante</button>
<p class = "demo" id="demo"></p>
</body>
</html>
最佳答案
我对你的代码做了三件事:
- 将
currentText = 0
和array
声明移出next
函数的作用域并移至全局作用域。 - 将显示新文本的部分移至其自己的函数中
- 当页面加载时使用
window.onload
调用显示函数
document.getElementById("botonatras").addEventListener("click", next);
var currentText = 0;
var array = ["text1", "text2", "text3"];
function display () {
document.getElementById("demo").innerHTML = array[currentText];
}
function next () {
var textMax = 3;
currentText = (currentText + 1) % textMax;
display();
}
window.onload = function () {
display();
}
.demo {
height: 200px;
width:300px;
background-color:lightblue;
font-family:tahoma;
text-align:center;
font-size:18px;
}
.boton{
width:200px;
height:50px;
border:solid;
border-radius:5px;
background-color: rgba(255,90,18,0.5);
border-color:red;
color:white;
}
<html>
<body>
<p>Aplicacion para realizar lecturas de aplicacion.</p>
<button id="botonatras" class ="boton">Atras</button>
<button id="myBtn" class ="boton">Adelante</button>
<p class = "demo" id="demo"></p>
</body>
</html>
关于javascript - 如何在 JavaScript 中创建一个来回移动的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41783313/