javascript - 隐藏的 Div 在 Javascript 与其他 Div 切换之前占用空间

标签 javascript jquery html css iframe

我有 2 个 Div,当我按下一个按钮时,它们会使用 javascript 在它们之间切换。

问题是在我按下按钮之前,隐藏的 div 占用了空间并弄乱了布局。

我附上了片段

function switchVisible() {
  if (document.getElementById('1')) {

    if (document.getElementById('1').style.display == 'none') {
      document.getElementById('1').style.display = 'block';
      document.getElementById('2').style.display = 'none';
    }
    else {
      document.getElementById('1').style.display = 'none';
      document.getElementById('1').style.display = 'none';
      document.getElementById('2').style.display = 'block';
    }
  }
}
<button type="submit" value="Click" onclick="switchVisible();" </button>
<div id="1">
  some content
</div> 

<div id="2" class="inner border">
  some content 2
</div>

最佳答案

您只需在第一次使用时隐藏它:

document.getElementById('2').style.display = 'none';

或者也使用内联样式(不推荐):

<div id="2" class="inner border" style='display:none'>

希望这对您有所帮助。

document.getElementById('2').style.display = 'none';

function switchVisible() {
  if (document.getElementById('1')) {

    if (document.getElementById('1').style.display == 'none') {
      document.getElementById('1').style.display = 'block';
      document.getElementById('2').style.display = 'none';
    }
    else {
      document.getElementById('1').style.display = 'none';
      document.getElementById('1').style.display = 'none';
      document.getElementById('2').style.display = 'block';
    }
  }
}
<button type="submit" value="Click" onclick="switchVisible();" </button>
<div id="1">
  some content
</div> 

<div id="2" class="inner border">
  some content 2
</div>

关于javascript - 隐藏的 Div 在 Javascript 与其他 Div 切换之前占用空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41027905/

相关文章:

javascript - 使用 Javascript/jQuery 使按钮出现在滚动条上

javascript - Jquery价格 slider 无法在移动设备中滚动

javascript - 不同机器上的两个浏览器查看同一个页面

javascript - 点击后关闭导航选项卡

javascript - 将日期时间选择器转换为 UTC 时间

javascript - Jquery Accordion 上的图标更改

html - 比 float :right in navigation bar? 更好的方法

javascript - 我的项目中的 href 链接不可点击

html - Bootstrap 背景图片

javascript - 创建的图像元素未放置在 div 内的正确位置