隐藏div可见时滚动到内容

时间:2016-06-03 13:58:07

标签: javascript html css

我对此并不是很了解,我无法弄清楚这一点。我有三个按钮和三个隐藏的div。单击按钮时,将显示隐藏的内容。如何向下滚动页面以使内容的开头位于页面顶部?

<script type="text/javascript">
function showDiv(num) {
    document.getElementById('div1').style.visibility='hidden';
    document.getElementById('div1').style.height='0px';
    document.getElementById('div1').style.overflow='hidden';
    document.getElementById('div2').style.visibility='hidden';
    document.getElementById('div2').style.height='0px';
    document.getElementById('div2').style.overflow='hidden';
    document.getElementById('div3').style.visibility='hidden';
    document.getElementById('div3').style.height='0px';
    document.getElementById('div3').style.overflow='hidden';
    document.getElementById('div'+num).style.visibility='visible';
    document.getElementById('div'+num).style.height='10px';
    document.getElementById('div'+num).style.overflow='visible';    
}
</script>

我的Css:

#div1, #div2, #div3 {
    visibility: hidden;
    height:0px;
    overflow:hidden

}

.button {
    background-color: green;
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 22px;
    cursor: pointer;
    font-family: Arial;
}

我的按钮:

<input type="button" class="button" name="Showdiv1" value="Show Div 1" onclick="showDiv('1')" />
<input type="button" class="button" name="Showdiv2" value="Show Div 2" onclick="showDiv('2')" />
<input type="button" class="button" name="Showdiv3" value="Show Div 3" onclick="showDiv('3')" />
<div id="div1"> I'm div1 </div>
<div id="div2"> I'm div2 </div>
<div id="div3"> <form style="margin-top:1000px;height: 1000px;" id="form1">
        Form with huge data in it
        </form> </div>

一个演示,其中div 3具有从页面下方开始的长格式:https://jsfiddle.net/cgrouge/Lx0pyg4L/

1 个答案:

答案 0 :(得分:1)

$(function() {
 $('a[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
  var target = $(this.hash);
  target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
  if (target.length) {
    $('html, body').animate({
      scrollTop: target.offset().top
    }, 1000);
    return false;
  }
}
});
});

编辑1:

Reference 您可以使用此脚本。它完美地适合您的目的。您需要将输入标记放在锚标记内。

编辑2:

Pen