如何在 JavaScrtipt 中创建一个来回移动的按钮



大家下午好。

我是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> 

我对你的代码做了三件事:

  1. currentText = 0array声明移出next函数的作用域并移入全局范围。
  2. 将显示新文本的部分移动到其自己的函数中
  3. 在页面加载时调用显示函数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>

在上面的级别定义变量 currentText

document.getElementById("botonatras").addEventListener("click", next);
var currentText = 0;
function next () {
var array = ["text1", "text2", "text3"];
 
  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> 

相关内容

  • 没有找到相关文章

最新更新