首页 > 解决方案 > 单击按钮显示下一个 div

问题描述

我无法创建一个可以让我进入下一个 div 的函数。

我已经尝试了一些东西,但由于某种原因我无法让它工作

<button type="button" name="button" onclick="arrowLeft()" id="arrowLeft">Prev</button>
<button type="button" name="button" onclick="arrowRight()" id="arrowRight">Next</button>

<div class="monsterTabs" id="monsterTabs">
  <div class="monsterType" id="monsterSlime" style="display:block;">
    Slime
  </div>
  <div class="monsterType" id="monsterZombie" style="display:none;">
    Zombie
  </div>
  <div class="monsterType" id="monsterSkeleton" style="display:none;">
    Skeleton
  </div>
  <div class="monsterType" id="monsterWolf" style="display:none;">
    Wolf
  </div>
</div>

https://jsfiddle.net/gfx873ve/3

我想知道制作它的最佳方法,这样我就可以毫无问题地通过 div。

标签: javascript

解决方案


您可以通过使用然后在调用and函数document.getElementsByClassName('monsterType');时更新每个怪物的显示属性来获取所有怪物的集合。arrowLeftarrowRight

我使用了一个monsterId变量来控制当前显示的怪物。中的每个元素monsters都将其 display 属性设置为,none除非它是monsterId列表中的第 -th 个元素。

monsterId = (monsterId + monsters.length) % monsters.length;行使用模数 (%) 运算符确保 monsterId 始终介于 0 和 monsters.length - 1 之间。

let monsters = document.getElementsByClassName('monsterType');
let monsterId = 0;

function arrowLeft() {
  updateMonster(-1);
}

function arrowRight() {
 updateMonster(1);
}

function updateMonster(direction) {  
  monsterId += direction;
  monsterId = (monsterId + monsters.length) % monsters.length;
  
  for(var i = 0; i < monsters.length; i++){
    monsters[i].style.display = i === monsterId ? 'block' : 'none';
  }  
}
<button type="button" name="button" onclick="arrowLeft()" id="arrowLeft">Prev</button>
<button type="button" name="button" onclick="arrowRight()" id="arrowRight">Next</button>


<div class="monsterTabs" id="monsterTabs">
  <div class="monsterType" id="monsterSlime" style="display:block;">
    Slime
  </div>
  <div class="monsterType" id="monsterZombie" style="display:none;">
    Zombie
  </div>
  <div class="monsterType" id="monsterSkeleton" style="display:none;">
    Skeleton
  </div>
  <div class="monsterType" id="monsterWolf" style="display:none;">
    Wolf
  </div>
</div>


推荐阅读