可点击的div,用于隐藏和显示内容

时间:2017-10-23 09:40:59

标签: javascript html css3

不确定为什么这不起作用,有时需要双击div来显示内容,任何建议原因,以及如何修复它? 。我希望它隐藏并显示#newpost div,当点击toggle1 div等等。谢谢



var button = document.getElementById('toggle1'); // Assumes element with id='button'

button.onclick = function() {
  var div = document.getElementById('newpost');
  if (div.style.display !== 'none') {
    div.style.display = 'none';
  } else {
    div.style.display = 'block';
  }

};

var button = document.getElementById('toggle2'); // Assumes element with id='button'

button.onclick = function() {
  var div = document.getElementById('newpost1');
  if (div.style.display !== 'none') {
    div.style.display = 'none';
  } else {
    div.style.display = 'block';
  }
};

<nav>
  <ul>
    <li id="toggle1">Home</li>

    <div id="newpost" class="post">
      <p>Lorem iporem ipsum dolor sit amet, consectetur adipisicing elit. Omnis id, dolorem dolores obcaecati, repellat quamorem ipsum dolor sit amet, consectetur adipisicing elit. Omnis id, dolorem dolores obcaecati, repellat quamsum dolor sit amet, consectetur
        adipisicing elit. Omnis id, dolorem dolores obcaecati, repellat quam!</p>
    </div>

    <li id="toggle2">Contact</li>
  </ul>
</nav>




<div id="newpost" class="post">
  <p>Lorem ipsum ble ble at quam!</p>
</div>

<br>


<div id="newpost1" class="post">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Omnis id, dolorem dolores obcaecati, repellat quam!</p>
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

嗯,也许你的按钮在开始时没有聚焦。尝试添加第一行:

curl -X POST -H "Content-Type: application/json" -d '{"key":"val"}' URL
document.querySelector('nav').focus();

var button = document.getElementById('toggle1'); // Assumes element with id='button'

button.onclick = function() {
  var div = document.getElementById('newpost');
  if (div.style.display !== 'none') {
    div.style.display = 'none';
  } else {
    div.style.display = 'block';
  }

};

var button = document.getElementById('toggle2'); // Assumes element with id='button'

button.onclick = function() {
  var div = document.getElementById('newpost1');
  if (div.style.display !== 'none') {
    div.style.display = 'none';
  } else {
    div.style.display = 'block';
  }
};