使用 html 滚动到特定元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24739126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 02:15:14  来源:igfitidea点击:

Scroll to a specific Element Using html

htmlcss

提问by M1rwen

Is there a method in html which makes the webpage scroll to a specific Element using HTML !?

html 中是否有一种方法可以使网页使用 HTML 滚动到特定元素!?

回答by EasyBB

Yes you use this

是的,你用这个

<a href="#google"></a>

<div id="google"></div>

But this does not create a smooth scroll just so you know.

但这并不能像您知道的那样创建平滑的滚动。

You can also add in your CSS

你也可以在你的 CSS 中添加

html {
  scroll-behavior: smooth;
}

回答by devsam247

<!-- HTML -->
<a href="#google"></a>
<div id="google"></div>

/*CSS*/
html { scroll-behavior: smooth; } 

Additionally, you can add html { scroll-behavior: smooth; } to your CSS to create a smooth scroll.

此外,您可以添加 html { scroll-behavior: smooth; 到您的 CSS 以创建平滑滚动。

回答by Tyblitz

You should mention whether you want it to smoothly scrollor simply jumpto an element. Jumping is easy & can be done just with HTML or Javascript. The simplest is to use anchor's. The limitation is that every element you want to scroll to has to have an id. A side effect is that #theIDwill be appended to the URL

您应该提及您是希望它平滑滚动还是简单地跳转到一个元素。跳转很容易,只需使用 HTML 或 Javascript 即可完成。最简单的是使用锚点。限制是您要滚动到的每个元素都必须有一个id. 副作用是#theID将附加到 URL

<a href="#scroll">Go to Title</a>
<div>
  <h1 id="scroll">Title</h1>
</div>

You can add CSS effects to the target when the link is clicked with the CSS :targetselector.

当使用 CSS:target选择器单击链接时,您可以向目标添加 CSS 效果。



With some basic JS you can do more, namely the method scrollIntoView(). Your elements don't need an id, though it is still easier, e.g.

使用一些基本的 JS,您可以做更多的事情,即 method scrollIntoView()。您的元素不需要 id,但它仍然更容易,例如

function onLinkClick() {
  document.getElementsByTagName('h2')[3].scrollIntoView();
  // will scroll to 4th h3 element
}


Finally, if you need smooth scrolling, you should have a look at JS Smooth Scrollor this snippetfor jQuery. (NB: there are probably many more).

最后,如果您需要平滑滚动,您应该查看JS Smooth Scroll或jQuery 的这个片段。(注意:可能还有更多)。

回答by Pedram Vdl

Add this to your javascript:

将此添加到您的 javascript 中:

$('.smooth-goto').on('click', function() {  
    $('html, body').animate({scrollTop: $(this.hash).offset().top - 50}, 1000);
    return false;
});

Also, don't forget to add this class to your a tag too like this:

另外,不要忘记将此类添加到您的 a 标签中,如下所示:

<a href="#id-of-element" class="smooth-goto">Text</a>

回答by sivako

Year 2020. Now we have element.scrollIntoView()method to scroll to specific element.

2020 年。现在我们有了element.scrollIntoView()滚动到特定元素的方法。

HTML

HTML

<div id="my_element">
</div>

JS

JS

var my_element = document.getElementById("my_element");

my_element.scrollIntoView({
  behavior: "smooth",
  block: "start",
  inline: "nearest"
});

Good thing is we can initiate this from any onclick/event and need not be limited to tag.

好消息是我们可以从任何 onclick/event 启动它,而不必限于标签。

回答by Nils Coussement

 <nav>
      <a href="#section1">1</a> 
      <a href="#section2">2</a> 
      <a href="#section3">3</a>
    </nav>
    <section id="section1">1</section>
    <section id="section2" class="fifty">2</section>
    <section id="section3">3</section>
    
    <style>
      * {padding: 0; margin: 0;}
      nav {
        background: black;
        position: fixed;
      }
      a {
        color: #fff;
        display: inline-block;
        padding: 0 1em;
        height: 50px;
      }
      section {
        background: red;
        height: 100vh;
        text-align: center;
        font-size: 5em;
      }
      
      #section1{
        background-color:green;
      }
      #section3{
        background-color:yellow;
      }
      
    </style>
    
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript" >
      $(document).on('click', 'a[href^="#"]', function (event) {
        event.preventDefault();
    
        $('html, body').animate({
            scrollTop: $($.attr(this, 'href')).offset().top
        }, 500);
      });
    </script>
      

回答by Ben

Yes, you may use an anchorby specifying the idattribute of an element and then linking to it with a hash.

是的,您可以通过指定元素的属性然后使用哈希链接到它来使用锚点id

For example (taken from the W3 specification):

例如(取自 W3 规范):

You may read more about this in <A href="#section2">Section Two</A>.
...later in the document
<H2 id="section2">Section Two</H2>
...later in the document
<P>Please refer to <A href="#section2">Section Two</A> above
for more details.

回答by Nicolas

By using an href attribute inside an anchor tag you can scroll the page to a specific element using a #in front of the elements id name.

通过在锚标记内使用 href 属性,您可以使用#元素 id 名称前面的 将页面滚动到特定元素。

Also, here is some jQuery/JS that will accomplish putting variables into a div.

此外,这里有一些 jQuery/JS 可以完成将变量放入 div 中。

<html>
<body>

Click <a href="#myContent">here</a> to scroll to the myContent section.

<div id="myContent">
...
</div>

<script>
    var myClassName = "foo";

    $(function() {
        $("#myContent").addClass(myClassName);
    });
</script>

</body>

回答by CYUBAHIRO Patrick

The above answers are good and correct. However, the code may not give the expected results. Allow me to add something to explain why this is very important.

上面的答案是好的和正确的。但是,代码可能不会给出预期的结果。请允许我添加一些内容来解释为什么这非常重要。

It is true that adding the scroll-behavior: smooth to the html element allows smooth scrolling for the whole page. However not all web browsers support smooth scrolling using HTML.

确实,将 scroll-behavior: smooth 添加到 html 元素可以使整个页面平滑滚动。然而,并非所有 Web 浏览器都支持使用 HTML 进行平滑滚动。

So if you want to create a website accessible to all user, regardless of their web browsers, it is highly recommended to use JavaScript or a JavaScript library such as jQuery, to create a solution that will work for all browsers.

因此,如果您想创建一个可供所有用户访问的网站,无论他们使用何种 Web 浏览器,强烈建议使用 JavaScript 或 JavaScript 库(如 jQuery)来创建适用于所有浏览器的解决方案。

Otherwise, some users may not enjoy the smooth scrolling of your website / platform.

否则,某些用户可能无法享受您的网站/平台的流畅滚动。

I can give a simpler example on how it can be applicable.

我可以举一个更简单的例子来说明它如何适用。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
</script>
<style>
#section1 {
height: 600px;
background-color: pink;
}
#section2 {
height: 600px;
background-color: yellow;
}
</style>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Smooth Scroll</h1>
<div class="main" id="section1">
<h2>Section 1</h2>
<p>Click on the link to see the "smooth" scrolling effect.</p>
<a href="#section2">Click Me to Smooth Scroll to Section 2 Below</a>
<p>Note: Remove the scroll-behavior property to remove smooth scrolling.</p>
</div>
<div class="main" id="section2">
<h2>Section 2</h2>
<a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>
</div>
</body>
</html>

回答by marko-36

Should you want to resort to using a plug-in, malihu-custom-scrollbar-plugin, could do the job. It performs an actual scroll, not just a jump. You can even specify the speed/momentum of scroll. It also lets you set up a menu (list of links to scroll to), which have their CSS changed based on whether the anchors-to-scroll-to are in viewport, and other useful features.

如果您想求助于使用插件,malihu-custom-scrollbar-plugin可以完成这项工作。它执行实际的滚动,而不仅仅是跳转。您甚至可以指定滚动的速度/动量。它还允许您设置一个菜单(要滚动到的链接列表),根据锚点到滚动到是否在视口中以及其他有用的功能来更改其 CSS。

There are demo on the author's siteand let our company site serve as a real-world exampletoo.

作者的网站上有demo,也让我们公司的网站作为一个真实的例子