单击带有哈希标记的箭头页面滚动

时间:2015-01-01 13:35:03

标签: javascript jquery html

我正在寻找一个jquery脚本来动画/滚动'在页面中,当点击箭头“哈希”时标记:

下面是在html

中放置背景图像的箭头代码
<div style="margin-top:380px;">
    <a href="#transparency">
        <div class="arrow-down-light-blue"></div>
    </a>
</div>

html页面中的Javascript

$(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;
      }
    }
  });
});

有没有可以帮我提供一个jquery脚本?

2 个答案:

答案 0 :(得分:0)

使用以下代码 使用.ready()函数绑定click事件并使用.scrollTop()向下滚动到所需的HTML元素

按以下方式更改HTML

 <div style="margin-top:380px;">
    <a id="anchorID" class="anchorClick" href="#transparency">
        <div class="arrow-down-light-blue">Click here</div>
    </a>
</div>
<div style="height:500px"></div>
<div id="transparency"> your transparency div here </div>

<div style="margin-top:380px;">
    <a id="anchorID1" class="anchorClick" href="#transparency1">
        <div class="arrow-down-light-blue">Click here</div>
    </a>
</div>
<div style="height:500px"></div>
<div id="transparency1" style="margin-bottom:100px;"> your transparency.1 div here </div>

的Javascript

$(document).ready(function(){
   $(".anchorClick").click(function(){
      $('html, body').animate({
       scrollTop: $($(this).attr('href')).offset().top // UPDATED LINE
      }, 2000);
   });
});

** 并且不要忘记在<head>标记的HTML页面顶部添加jQuery Library:)

更新后的答案:使用ClassName选择器

<强> See the updated JS Fiddle here

答案 1 :(得分:0)

取出带有余量顶部的div用于演示,这适用于类,因此可扩展。编辑后添加回顶部

&#13;
&#13;
$(document).ready(function(){
   $(".anchor").click(function(e){
      $('html, body').animate({
       scrollTop: $($(this).attr('href')).offset().top
      }, 1000);
   });
});
&#13;
#top{background-color:red;}
#middle{background-color:yellow;}
#bottom{background-color:green;}
div.block{height:400px;}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="toppage"></div>
<a class="anchor" href="#top"> 
        <div class="arrow-down-light-blue">top</div>
    </a>


    <a class="anchor" href="#middle">
        <div class="arrow-down-light-blue">middle</div>
   

    <a class="anchor" href="#bottom">
        <div class="arrow-down-light-blue">bottom</div>
    </a>

<div class="block" id="top">The top
  <a class="anchor" href="#toppage"> Back to top</a>
      </div>
<div class="block" id="middle">The middle
      <a class="anchor" href="#toppage"> Back to top</a>
      </div>
<div  class="block" id="bottom">The bottom
      <a class="anchor" href="#toppage"> Back to top</a>
      </div>
&#13;
&#13;
&#13;