使用html滚动到特定元素

问题描述 投票:24回答:6

在html中是否有一个方法使网页使用HTML滚动到特定的元素!

html5 css3
6个回答
44
投票

是的你用这个

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

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

但这并不能创造一个平滑的卷轴,所以你知道。


19
投票

你应该提一下是否希望它顺利滚动或只是跳转到一个元素。跳转很简单,只需使用HTML或Javascript就可以完成。最简单的是使用锚点。限制是您要滚动到的每个元素都必须具有id。副作用是#theID将附加到URL

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

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


有了一些基本的JS,你可以做更多,即方法scrollIntoView()。您的元素不需要id,但它仍然更容易,例如

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

最后,如果你需要平滑滚动,你应该看看jaz的JS Smooth Scrollthis snippet。 (注意:可能还有更多)。


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

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

另外,你可以添加html {scroll-behavior:smooth;你的CSS创建一个平滑的滚动。


9
投票

将其添加到您的javascript:

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

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

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

1
投票

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

例如(取自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.

1
投票

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

此外,这里有一些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>

0
投票
<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>
© www.soinside.com 2019 - 2024. All rights reserved.