如何将 HTML 页面滚动到给定的锚点

发布于 2024-09-08 02:55:08 字数 346 浏览 4 评论 0原文

我想让浏览器将页面滚动到给定的锚点,只需使用 JavaScript。

我已在 HTML 代码中指定了 nameid 属性:

 <a name="anchorName">..</a>

或者

 <h1 id="anchorName2">..</h1>

我希望获得与导航到 http 所获得的相同效果: //server.com/path#anchorName。应滚动页面,以便锚点位于页面可见部分的顶部附近。

I’d like to make the browser to scroll the page to a given anchor, just by using JavaScript.

I have specified a name or id attribute in my HTML code:

 <a name="anchorName">..</a>

or

 <h1 id="anchorName2">..</h1>

I’d like to get the same effect as you’d get by navigating to http://server.com/path#anchorName. The page should be scrolled so that the anchor is near the top of the visible part of the page.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

梦言归人 2024-09-15 02:55:08
function scrollTo(hash) {
    location.hash = "#" + hash;
}

根本不需要 jQuery!

function scrollTo(hash) {
    location.hash = "#" + hash;
}

No jQuery required at all!

格子衫的從容 2024-09-15 02:55:08

方法更简单:

var element_to_scroll_to = document.getElementById('anchorName2');
// Or:
var element_to_scroll_to = document.querySelectorAll('.my-element-class')[0];
// Or:
var element_to_scroll_to = $('.my-element-class')[0];
// Basically `element_to_scroll_to` just have to be a reference
// to any DOM element present on the page
// Then:
element_to_scroll_to.scrollIntoView();

Way simpler:

var element_to_scroll_to = document.getElementById('anchorName2');
// Or:
var element_to_scroll_to = document.querySelectorAll('.my-element-class')[0];
// Or:
var element_to_scroll_to = $('.my-element-class')[0];
// Basically `element_to_scroll_to` just have to be a reference
// to any DOM element present on the page
// Then:
element_to_scroll_to.scrollIntoView();
快乐很简单 2024-09-15 02:55:08

您可以使用 jQuery 的 .animate().offset()scrollTop。示例

$(document.body).animate({
    'scrollTop':   $('#anchorName2').offset().top
}, 2000);

链接:http://jsbin.com/unasi3/edit

如果您不想动画,使用 .scrollTop() ,例如:

$(document.body).scrollTop($('#anchorName2').offset().top);

或 JavaScript 的本机 location.hash 喜欢:

location.hash = '#' + anchorid;

You can use jQuery's .animate(), .offset() and scrollTop. Like

$(document.body).animate({
    'scrollTop':   $('#anchorName2').offset().top
}, 2000);

Example link: http://jsbin.com/unasi3/edit

If you don't want to animate, use .scrollTop() like:

$(document.body).scrollTop($('#anchorName2').offset().top);

Or JavaScript's native location.hash like:

location.hash = '#' + anchorid;
影子的影子 2024-09-15 02:55:08

2018年至今纯JavaScript:

有一种非常方便的方式滚动到元素:

el.scrollIntoView({
  behavior: 'smooth', // smooth scroll
  block: 'start' // the upper border of the element will be aligned at the top of the visible part of the window of the scrollable area.
})

但据我了解,它没有像下面的选项那样好的支持。

输入图像描述此处

了解有关该方法的更多信息。


如果需要该元素位于顶部:

const element = document.querySelector('#element')
const topPos = element.getBoundingClientRect().top + window.pageYOffset

window.scrollTo({
  top: topPos, // scroll so that the element is at the top of the view
  behavior: 'smooth' // smooth scroll
})

CodePen 上的演示示例


如果您想要要位于中心的元素:

const element = document.querySelector('#element')
const rect = element.getBoundingClientRect() // get rects(width, height, top, etc)
const viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);

window.scroll({
  top: rect.top + rect.height / 2 - viewHeight / 2,
  behavior: 'smooth' // smooth scroll
});

CodePen 上的演示示例


支持:

введите сюда описание изображения

他们写道,scrollscrollTo 的方法相同,但 scrollTo 中的支持效果更好。

有关该方法的更多信息

2018-now Pure JavaScript:

There is a very convenient way to scroll to the element:

el.scrollIntoView({
  behavior: 'smooth', // smooth scroll
  block: 'start' // the upper border of the element will be aligned at the top of the visible part of the window of the scrollable area.
})

But as far as I understand, it does not have such good support as the options below.

Enter image description here

Learn more about the method.


If it is necessary that the element is in the top:

const element = document.querySelector('#element')
const topPos = element.getBoundingClientRect().top + window.pageYOffset

window.scrollTo({
  top: topPos, // scroll so that the element is at the top of the view
  behavior: 'smooth' // smooth scroll
})

Demonstration example on CodePen


If you want the element to be in the center:

const element = document.querySelector('#element')
const rect = element.getBoundingClientRect() // get rects(width, height, top, etc)
const viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);

window.scroll({
  top: rect.top + rect.height / 2 - viewHeight / 2,
  behavior: 'smooth' // smooth scroll
});

Demonstration example on CodePen


Support:

введите сюда описание изображения

They write that scroll is the same method as scrollTo, but support shows better in scrollTo.

More about the method.

゛时过境迁 2024-09-15 02:55:08

jAndy 的解决方案 ,但平滑滚动似乎在 Firefox 中出现问题。

这种方式在 Firefox 中也适用。

(function($) {
    $(document).ready(function() {
         $('html, body').animate({
           'scrollTop':   $('#anchorName2').offset().top
         }, 2000);
    });
})(jQuery);

Great solution by jAndy, but the smooth scroll seems to be having issues working in Firefox.

Writing it this way works in Firefox as well.

(function($) {
    $(document).ready(function() {
         $('html, body').animate({
           'scrollTop':   $('#anchorName2').offset().top
         }, 2000);
    });
})(jQuery);
眼波传意 2024-09-15 02:55:08

让浏览器将页面滚动到给定锚点的最简单方法是在 style.css 文件中添加 *{scroll-behavior: smooth;} 和您的 HTML 导航使用 #NameOfTheSection

*{scroll-behavior: smooth;}
<a href="#scroll-to">Click to Scroll</a>

<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>

<section id="scroll-to">
<p>it will scroll down to this section</p>
</section>

The easiest way to to make the browser to scroll the page to a given anchor is to add *{scroll-behavior: smooth;} in your style.css file and in your HTML navigation use #NameOfTheSection.

*{scroll-behavior: smooth;}
<a href="#scroll-to">Click to Scroll</a>

<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>
<p>other sections</p>

<section id="scroll-to">
<p>it will scroll down to this section</p>
</section>

﹏半生如梦愿梦如真 2024-09-15 02:55:08

在 2018 年,你不需要 jQuery 来完成这样简单的事情。内置的 scrollIntoView()方法支持“behavior”属性以平滑滚动到页面上的任何元素。您甚至可以使用哈希值更新浏览器 URL,使其可添加书签。

来自 有关滚动 HTML 书签的教程,这是一种本机方法自动为页面上的所有锚链接添加平滑滚动:

let anchorlinks = document.querySelectorAll('a[href^="#"]')
 
for (let item of anchorlinks) { // relitere 
    item.addEventListener('click', (e)=> {
        let hashval = item.getAttribute('href')
        let target = document.querySelector(hashval)
        target.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        })
        history.pushState(null, null, hashval)
        e.preventDefault()
    })
}

In 2018, you don't need jQuery for something simple like this. The built in scrollIntoView() method supports a "behavior" property to smoothly scroll to any element on the page. You can even update the browser URL with a hash to make it bookmarkable.

From this tutorial on scrolling HTML Bookmarks, here is a native way to add smooth scrolling to all anchor links on your page automatically:

let anchorlinks = document.querySelectorAll('a[href^="#"]')
 
for (let item of anchorlinks) { // relitere 
    item.addEventListener('click', (e)=> {
        let hashval = item.getAttribute('href')
        let target = document.querySelector(hashval)
        target.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        })
        history.pushState(null, null, hashval)
        e.preventDefault()
    })
}
女皇必胜 2024-09-15 02:55:08

这是一个没有 jQuery 的纯 JavaScript 解决方案。它已在 Chrome 和 Internet Explorer 上进行了测试,但未在 iOS 上进行了测试。

function ScrollTo(name) {
  ScrollToResolver(document.getElementById(name));
}

function ScrollToResolver(elem) {
  var jump = parseInt(elem.getBoundingClientRect().top * .2);
  document.body.scrollTop += jump;
  document.documentElement.scrollTop += jump;
  if (!elem.lastjump || elem.lastjump > Math.abs(jump)) {
    elem.lastjump = Math.abs(jump);
    setTimeout(function() { ScrollToResolver(elem);}, "100");
  } else {
    elem.lastjump = null;
  }
}

演示:https://jsfiddle.net/jd7q25hg/12/

Here is a pure JavaScript solution without jQuery. It was tested on Chrome and Internet Explorer, but not tested on iOS.

function ScrollTo(name) {
  ScrollToResolver(document.getElementById(name));
}

function ScrollToResolver(elem) {
  var jump = parseInt(elem.getBoundingClientRect().top * .2);
  document.body.scrollTop += jump;
  document.documentElement.scrollTop += jump;
  if (!elem.lastjump || elem.lastjump > Math.abs(jump)) {
    elem.lastjump = Math.abs(jump);
    setTimeout(function() { ScrollToResolver(elem);}, "100");
  } else {
    elem.lastjump = null;
  }
}

Demo: https://jsfiddle.net/jd7q25hg/12/

各自安好 2024-09-15 02:55:08

平滑滚动到正确位置

获取正确y坐标并使用window.scrollTo({top: y,behavior: 'smooth'})

const id = 'anchorName2';
const yourElement = document.getElementById(id);
const y = yourElement.getBoundingClientRect().top + window.pageYOffset;

window.scrollTo({top: y, behavior: 'smooth'});

Smoothly scroll to the proper position

Get correct y coordinate and use window.scrollTo({top: y, behavior: 'smooth'})

const id = 'anchorName2';
const yourElement = document.getElementById(id);
const y = yourElement.getBoundingClientRect().top + window.pageYOffset;

window.scrollTo({top: y, behavior: 'smooth'});
憧憬巴黎街头的黎明 2024-09-15 02:55:08

大多数答案都过于复杂。

如果您只想跳转到目标元素,则不需要JavaScript:

# the link:
<a href="#target">Click here to jump.</a>

# target element:
<div id="target">Any kind of element.</div>

如果您想动画滚动到目标,请参考5hahiL的回答

Most answers are unnecessarily complicated.

If you just want to jump to the target element, you don't need JavaScript:

# the link:
<a href="#target">Click here to jump.</a>

# target element:
<div id="target">Any kind of element.</div>

If you want to scroll to the target animatedly, please refer to 5hahiL's answer.

暗恋未遂 2024-09-15 02:55:08
$(document).ready ->
  $("a[href^='#']").click ->
    $(document.body).animate
      scrollTop: $($(this).attr("href")).offset().top, 1000
$(document).ready ->
  $("a[href^='#']").click ->
    $(document.body).animate
      scrollTop: $($(this).attr("href")).offset().top, 1000
旧街凉风 2024-09-15 02:55:08

CSS-Tricks 的解决方案在 jQuery 2.2.0 中不再有效。它会抛出选择器错误:

JavaScript 运行时错误:语法错误,无法识别的表达式:a[href*=#]:not([href=#])

我通过更改选择器修复了它。完整的片段是这样的:

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

The solution from CSS-Tricks no longer works in jQuery 2.2.0. It will throw a selector error:

JavaScript runtime error: Syntax error, unrecognized expression: a[href*=#]:not([href=#])

I fixed it by changing the selector. The full snippet is this:

$(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;
    }
  }
 });
});
忘你却要生生世世 2024-09-15 02:55:08

这有效:

$('.scroll').on("click", function(e) {

  e.preventDefault();

  var dest = $(this).attr("href");

  $("html, body").animate({

    'scrollTop':   $(dest).offset().top

  }, 2000);

});

https://jsfiddle.net/68pnkfgd/

只需将“scroll”类添加到任何链接你想要动画

This works:

$('.scroll').on("click", function(e) {

  e.preventDefault();

  var dest = $(this).attr("href");

  $("html, body").animate({

    'scrollTop':   $(dest).offset().top

  }, 2000);

});

https://jsfiddle.net/68pnkfgd/

Just add the class 'scroll' to any links you wish to animate

御弟哥哥 2024-09-15 02:55:08
jQuery("a[href^='#']").click(function(){
    jQuery('html, body').animate({
        scrollTop: jQuery( jQuery(this).attr('href') ).offset().top
    }, 1000);
    return false;
});

jQuery("a[href^='#']").click(function(){
    jQuery('html, body').animate({
        scrollTop: jQuery( jQuery(this).attr('href') ).offset().top
    }, 1000);
    return false;
});

墟烟 2024-09-15 02:55:08

这是一个可以将页面滚动到锚点的工作脚本。
要进行设置,只需为锚点链接提供一个与您要滚动到的锚点的名称属性相匹配的 id 即可。

<script>
    jQuery(document).ready(function ($){
        $('a').click(function (){
            var id = $(this).attr('id');
            console.log(id);
            if ( id == 'cet' || id == 'protein' ) {
                $('html, body').animate({ scrollTop: $('[name="' + id + '"]').offset().top}, 'slow');
            }
        });
    });
</script>

This is a working script that will scroll the page to the anchor.
To set it up, just give the anchor link an id that matches the name attribute of the anchor that you want to scroll to.

<script>
    jQuery(document).ready(function ($){
        $('a').click(function (){
            var id = $(this).attr('id');
            console.log(id);
            if ( id == 'cet' || id == 'protein' ) {
                $('html, body').animate({ scrollTop: $('[name="' + id + '"]').offset().top}, 'slow');
            }
        });
    });
</script>
往日情怀 2024-09-15 02:55:08

我发现了一个简单的 CSS-Tricks 上的 jQuery 解决方案。我现在用的就是这个。

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

I found an easy and simple jQuery solution on CSS-Tricks. That's the one I'm using now.

$(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;
      }
    }
  });
});
初熏 2024-09-15 02:55:08

Vue.js 2 解决方案...添加一个简单的数据属性来简单地强制更新:

  const app = new Vue({
  ...

  , updated: function() {
           this.$nextTick(function() {
           var uri = window.location.href
           var anchor = ( uri.indexOf('#') === -1 ) ? '' : uri.split('#')[1]
           if ( String(anchor).length > 0 && this.updater === 'page_load' ) {
              this.updater = "" // only on page-load !
              location.href = "#"+String(anchor)
           }
         })
        }
     });
     app.updater = "page_load"

 /* Smooth scrolling in CSS - it works in HTML5 only */
 html, body {
     scroll-behavior: smooth;
 }

A Vue.js 2 solution ... add a simple data property to simply force the update:

  const app = new Vue({
  ...

  , updated: function() {
           this.$nextTick(function() {
           var uri = window.location.href
           var anchor = ( uri.indexOf('#') === -1 ) ? '' : uri.split('#')[1]
           if ( String(anchor).length > 0 && this.updater === 'page_load' ) {
              this.updater = "" // only on page-load !
              location.href = "#"+String(anchor)
           }
         })
        }
     });
     app.updater = "page_load"

 /* Smooth scrolling in CSS - it works in HTML5 only */
 html, body {
     scroll-behavior: smooth;
 }
与风相奔跑 2024-09-15 02:55:08

假设我们有一个 id 为“hero”的元素。页面上任意位置的按钮,其 ID 为“skip”。

在JS中:

const btn = document.querySelector('#skip')
let skipto = document.querySelector('#hero')
skipto.scrollIntoView({ behavior: "smooth" })

Assume we have an element with id 'hero'. A button anywhere on the page with id 'skip'.

in JS:

const btn = document.querySelector('#skip')
let skipto = document.querySelector('#hero')
skipto.scrollIntoView({ behavior: "smooth" })
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文