单击特定链接显示并滚动到<div>

时间:2017-03-13 08:45:41

标签: javascript jquery html ajax

我有很多很多链接到同一页面上的不同div。 div是隐藏的,通过点击链接,它会滚动到该div并显示出来。

示例HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div id="first_div">
My content with huge text
My content with huge text
My content with huge text
My content with huge text
My content with huge text
My content with huge text
My content with huge text
My content with huge text
My content with huge text
</div>

<p><a href="#first_div">see content with huge text</a></p>

例如:我位于页面底部并单击其中一个链接,页面滚动到该页面并显示它(之前隐藏)。不同的链接当然会导致不同的div。

1 个答案:

答案 0 :(得分:1)

首先将Class添加到要隐藏的所有段落并设置display:none css属性。

设置事件后单击链接然后获取它的href(指示要显示的parag),然后显示并滚动到此段落。

请参阅下面的代码段可能会帮助您了解其工作原理:

$(document).ready(function(){
   $("a").click(function() {
      if(this.href.split("#")[1]) {
       
        var id= "#"+this.href.split("#")[1];
        
        $(id).fadeIn(2000);
        $('html, body').animate({
            scrollTop: $(id).offset().top
        } , 1000);
        
      }
    });
})
.hidden {
  display:none;
  color:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<p><a href="#first_div">see content with huge text</a></p>

<br><br><br><br><br><br><br><br><br><br>
Texts
<br><br><br><br><br><br><br><br><br><br><br><br><br>
Div after will shown up <br><br>
<div class="hidden" id="first_div">
My content with huge text
My content with huge text
My content with huge text
My content with huge text
My content with huge text
My content with huge text
My content with huge text
My content with huge text
My content with huge text
</div>