简体   繁体   English

从列表中一次显示一个元素/div

[英]Show one element/div at a time from list

I'm trying to make a single code hide all elements with the same class but show the one element by ID.我试图让单个代码隐藏具有相同类的所有元素,但按 ID 显示一个元素。 The way it's implemented right now it just stacks the divs on top of each other.它现在的实现方式只是将 div 堆叠在一起。 Anyway to show just one div at a time?无论如何一次只显示一个 div?

<script>
function CurtindoAlesadoDesktop() {
  var x = document.getElementById("curtindo-a-vida-alesado");
  if (x.style.display === "block") {
    x.style.display = "none";
  } else {
    x.style.display = "block";
  }
}
</script>

Link in use: maninhoflix.com.br (desktop only)使用中的链接:maninhoflix.com.br(仅限桌面)

Perhaps something like the following?也许类似于以下内容?

function showIdAndHideOthers(idToShow) {
  const elementsToHide = document.getElementsByClassName('class-to-hide');
  const elementToShow = document.getElementById(idToShow);
  for (const el of elementsToHide) {
    el.style.display = 'none';
  }
  elementToShow.style.display = 'block';
}

Alternatively, you could use two CSS classes, one which hides all elements by default, and another which shows the active element.或者,您可以使用两个 CSS 类,一个默认隐藏所有元素,另一个显示活动元素。 Then, you can keep track of the most recently shown element and simply add/remove a class.然后,您可以跟踪最近显示的元素并简单地添加/删除一个类。

For example (CSS):例如(CSS):

.thing {
  display: none;
}

.thing.selected {
  display: block;
}

JS: JS:

let lastElement;
function showIdAndHideOthers(idToShow) {
  const elementToShow = document.getElementById(idToShow);
  if (lastElement != null) {
    lastElement.classList.remove('selected');
  }
  elementToShow.classList.add('selected');
  lastElement = elementToShow;
}

EDIT: Example for the second: https://codepen.io/minism/pen/GRgGdPg编辑:第二个示例: https : //codepen.io/minism/pen/GRgGdPg

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM