javascript - 当隐藏的 div 可见时滚动到内容

标签 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/

最佳答案

$(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 你可以使用这个脚本。它非常适合您的目的。您需要将输入标签放在 anchor 标签内。

编辑 2:

Pen

关于javascript - 当隐藏的 div 可见时滚动到内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37616353/

相关文章:

javascript - 删除伪类(悬停)Javascript

css - 图像和 div 之间的奇数空间 (CSS)

javascript - JQuery UI - .resizable 不工作

javascript - 紧邻 html 标签下的 div 标签的合法性

javascript - 为什么 Meteor 集合没有在第一次 render() 时填充?

javascript - HTML 脚本标签和非 JS 内容 - Firefox

javascript - div 复选框在单击时变暗

html - Chrome 选择(下拉)滚动条不能改变/检查高度/元素和外观

javascript - AngularJS 函数在 javascript 加载后不应用?

JavaScript 返回 false 但仍在提交