javascript - 如何在 JavaScript 中创建一个来回移动的按钮

标签 javascript arrays navigation

大家下午好。

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

关于javascript - 如何在 JavaScript 中创建一个来回移动的按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41783313/

相关文章:

javascript - 通过纯 javascript 平滑地更改图像

javascript - 在 Ubuntu 16.04 中安装 SpiderMonkey 45 失败

javascript - 使用 JavaScript 将 HTML div 排序到相应的 div

c - 如何管理二维字符数组?

vba - Word 2016 中的导航 Pane : VBA code to force collapsed view of headings

javascript - Bootstrap 不会在 Angular 6 上加载

php - 数组元素中的未定义索引

javascript 序列化 - 一个简短的库

jsf-2 - java.lang.NullPointerException : Argument Error: Parameter id is null 异常

asp.net-mvc-4 - Durandal.js : change navigation options per area