切换网格显示(我缺少什么?)

时间:2018-07-30 07:06:10

标签: javascript css grid toggle display

编写一些代码来切换是否显示图像网格。它是一个6x8的网格,所以我在这里不包括72 div元素。当不显示图像网格时,将显示一个文本列表。因此更改了按钮文本。找不到任何错误。

<!DOCTYPE html>
<html>
<head>
<style>
#photo-index {
  display: grid;
  grid-template-columns: auto auto auto auto auto auto;
  grid-gap: 0px;
  background-color: #4f6b6f;
}
#toggle-button {
    color: white;
    background-color: rgba(0,0,0,.75);
    border-radius: 3px;
    text-align: center;
    padding: 15px;
    margin: auto;
    position: absolute;
    right: 5%;
    cursor: pointer;
}
</style>    
<script>
function toggleDisplay() {
    var pi = document.getElementById('photo-index');
    var displaySetting = pi.style.display;
    var toggle-button = document.getElementById('toggle-button');
    var showTaxonomy = 'Show Taxonomy';
    var showImages = 'Show Images';
    if (displaySetting == 'none') {
    pi.style.display = 'grid';
    toggle-button.innerHTML = showImages;
    }
    else {
    pi.style.display = 'none';
    toggle-button.innerHTML = showTaxonomy;
    }
}
</script>
</head>
<body>
<div onclick="toggleDisplay()" id="toggle-button">Show Taxonomy</div>
<div id="photo-index">Large Grid of Stuff</div>
</body>
</html>

1 个答案:

答案 0 :(得分:3)

变量声明toggle-button中的错误在JavaScript中不是有效变量,因此请使用toggle_button。 JavaScript变量不允许在变量声明中使用连字符,因为它被视为算术运算符。

function toggleDisplay() {
    var pi = document.getElementById('photo-index');
    var displaySetting = pi.style.display;
    var toggle_button = document.getElementById('toggle-button');
    var showTaxonomy = 'Show Taxonomy';
    var showImages = 'Show Images';
    if (displaySetting == 'none') {
    pi.style.display = 'grid';
      toggle_button.innerHTML = showImages;
    }
    else {
      pi.style.display = 'none';
      toggle_button.innerHTML = showTaxonomy;
    }
}
#photo-index {
  display: grid;
  grid-template-columns: auto auto auto auto auto auto;
  grid-gap: 0px;
  background-color: #4f6b6f;
}
#toggle-button {
    color: white;
    background-color: rgba(0,0,0,.75);
    border-radius: 3px;
    text-align: center;
    padding: 15px;
    margin: auto;
    position: absolute;
    right: 5%;
    cursor: pointer;
}
<div onclick="toggleDisplay()" id="toggle-button">Show Taxonomy</div>
<div id="photo-index">Large Grid of Stuff</div>