如何避免在调整页面大小时滚动



我有两个水平堆叠的divs

每个div都占据视口的 100%。

.section{
width:100%;
height:100%;
}

在每个div都有一个指向另一个div 的锚点。

<div class="first section ">
<a name="first-section">&nbsp;</a>
<p>Click <a href="#second-section">here</a> to go to the second section</p> 
</div>
<div class="second section">
<p>Click <a href="#first-section">here</a> to go to the first section</p> 
</div>
<a name="second-section">&nbsp;</a>

我的目标是每次只显示一个div的内容。但是,当一个位于第二部分div并调整页面大小时,当页面大小调整为其初始大小时,将显示两个divs

如何避免在调整页面大小时向上滚动?我有body{overflow:hidden;}.谢谢。

您可以将div 设置为 position:fixed ,因此它始终相对于视口。然后默认隐藏除第一个div 之外的所有div,并在 :target 上时显示该div

js小提琴示例

html, body { height: 100%; }
body { margin: 0; }
.section {
  width: 100%;
  height: 100%;
  position: fixed;
}
.section:target {
  visibility: visible;
}
.first {
  background: lightblue;
}
.second {
  background: lightgreen;
  visibility: hidden;
}
<div class="first section" id="first-section">
  <p>Click <a href="#second-section">here</a> to go to the second section</p>
</div>
<div class="second section" id="second-section">
  <p>Click <a href="#first-section">here</a> to go to the first section</p>
</div>

或者,使用具有不同值的z-index,并在div 位于 :target 上时将其移动到顶部。

js小提琴示例

html, body { height: 100%; }
body { margin: 0; }
.section {
  width: 100%;
  height: 100%;
  position: fixed;
}
.section:target {
  z-index: 3;
}
.first {
  background: lightblue;
  z-index: 2;
}
.second {
  background: lightgreen;
  z-index: 1;
}
<div class="first section" id="first-section">
  <p>Click <a href="#second-section">here</a> to go to the second section</p>
</div>
<div class="second section" id="second-section">
  <p>Click <a href="#first-section">here</a> to go to the first section</p>
</div>


请注意,这两种方法都要求每个div 都定义一个纯色背景。

最新更新