纯CSS选项卡 - 防止在选项卡更改时滚动到页面顶部

时间:2015-04-04 11:51:18

标签: html css tabs

我的案例完全在标题中描述:更改标签时,页面滚动到顶部,我不知道如何防止它...

.ubdtabs {
  
  float: none;
  list-style: none;
  position: relative;
  text-align: left;
  padding-left: 8px;
}
.ubdtabs li {
  float: left;
  display: block;
}
.ubdtabs input[type="radio"] {
  position: absolute;
  top: -9999px;
  left: -9999px;
}
.ubdtabs label {
  display: block;
  padding: 14px 21px;

  
  font-weight: normal;
  text-transform: uppercase;
  background: -webkit-linear-gradient(top, #1B6889 0%,#009DE0 100%);
  cursor: pointer;
  position: relative;
  
/*  -moz-transition: all 0.2s ease-in-out;
  -o-transition: all 0.2s ease-in-out;
  -webkit-transition: all 0.2s ease-in-out;
  transition: all 0.2s ease-in-out;*/
  text-shadow: 1px 1px 1px rgba(255,255,255,0.3);
  border-radius: 5px 5px 0 0;
  box-shadow: 2px 0 2px rgba(0,0,0,0.1), -2px 0 2px rgba(0,0,0,0.1);
}
.ubdtabs label:hover {
  background: #1B6889;
}
.ubdtabs .ubdtab-content {
  z-index: 2;
  display: none;
  overflow: hidden;
  width: 100%;
  
  line-height: 25px;
  padding: 25px;
  position: absolute;
  
  left: 0;
  background: #b3d4fc;
}
.ubdtabs [id^="ubdtab"]:checked + label {
  
  
  background: #b3d4fc;
}
.ubdtabs [id^="ubdtab"]:checked ~ [id^="ubdtab-content"] {
  display: block;
}
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<ul class="ubdtabs">
    <li>
        <input type="radio" name="ubdtabs" id="ubdtab1" checked />
        <label for="ubdtab1">first</label>
        <div id="ubdtab-content1" class="ubdtab-content">
        <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> 
        </div>
    </li>
  
    <li>
        <input type="radio" name="ubdtabs" id="ubdtab2" />
        <label for="ubdtab2">second</label>
        <div id="ubdtab-content2" class="ubdtab-content">
		<br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> <br> 	
        </div>
    </li>
</ul>

<br style="clear: both;" />

或者在Codepen:http://codepen.io/anon/pen/KwLPBQ

重现:
1.向下滚动页面 2.单击“第二个”选项卡
3.页面滚动到顶部

任何想法?

1 个答案:

答案 0 :(得分:4)

删除顶部&amp;左侧样式并将display:none;添加到收音机输入。如果您关注视口外部的输入,则会启用滚动条,然后滚动到该元素。

如果您想要聚焦视口外的元素,请使用此javascript代码

var donotScroll = function(element) {
  var x = window.scrollX, y = window.scrollY;
  element.focus();
  window.scrollTo(x, y);
}