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

Page scroll on click of an arrow which has hash tag

本文关键字:滚动 哈希标 单击      更新时间:2023-09-26

我正在寻找一个jquery脚本来在页面中"动画/滚动",当单击"哈希"标签的箭头时:

下面是放置在 html 中背景图像上方的箭头代码

<div style="margin-top:380px;">
    <a href="#transparency">
        <div class="arrow-down-light-blue"></div>
    </a>
</div>

JavaScript in html page

$(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脚本吗?

使用以下代码使用 .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>

爪哇语

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

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

更新答案:使用ClassName选择器

在此处查看更新的 JS 小提琴

取出了

边距顶部的div 进行演示,这适用于类,因此可扩展。 编辑以添加回顶部

$(document).ready(function(){
   $(".anchor").click(function(e){
      $('html, body').animate({
       scrollTop: $($(this).attr('href')).offset().top
      }, 1000);
   });
});
#top{background-color:red;}
#middle{background-color:yellow;}
#bottom{background-color:green;}
div.block{height:400px;}
<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>