滚动到一个位置在HTML文件-滚动动画

Scroll To a Location in HTML file - with Scrolling Animation

本文关键字:滚动 HTML 文件 动画 位置 一个      更新时间:2023-09-26

我目前试图有一个我的网站文本的一部分,当点击滚动到网站的某个位置。我有这段代码可以工作,但只是跳转,这从用户界面拿走了。

下面是我目前拥有的代码:

<a href="#part1">Go to Part One!</a>
<div id="part1">Hey Yeah!</div>

请知道,我不这样写代码,这只是一个例子。

定义如下函数:

function scrollToBox(element, offset) {
    var destination = $(element).offset().top - (offset ? offset : 120);
    $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination }, 1500);
}

然后在onclick事件中,您可以像下面这样调用它:

scrollToBox('#part1', 0);

提供了一个PLUNKER和一个使用jQuery animate()的代码片段。详细信息见源文件的注释。

片段

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1, maximum-scale=1, user-scalable=0" />
  <link href='https://fonts.googleapis.com/css?family=Quicksand:300' rel='stylesheet' />
  <style>
    /* Core~~~~~~~~~~~~~~~*/
    html {
      box-sizing: border-box;
      font: 300 16px/1.428'Quicksand';
      height: 100vh;
      width: 100vw;
    }
    *,
    *:before,
    *:after {
      box-sizing: inherit;
      margin: 0;
      padding: 0;
    }
    body {
      position: relative;
      font-size: 1rem;
      line-height: 1;
      height: 100vh;
      width: 100vw;
      overflow-x: hidden;
      overflow-y: scroll;
      -webkit-font-smoothing: antialiased;
      -moz-osx-font-smoothing: grayscale;
      background: #000;
      color: #eee;
      display: table;
    }
    h1,
    h2,
    h3,
    h4,
    h5,
    h6,
    legend {
      font-variant: small-caps;
      margin-bottom: 15px;
      color: #Fc3;
      text-align: center;
    }
    h1 {
      font-size: 1.5rem;
    }
    h2 {
      font-size: 1.4rem;
    }
    h3 {
      font-size: 1.3rem;
    }
    legend {
      font-size: 1.35rem;
    }
    p {
      margin: 0 5px 15px;
    }
    img {
      display: block;
      max-width: 100%;
      height: auto;
      margin: 20px auto;
    }
    a {
      color: #Fc0;
      text-decoration: none;
      margin: 10px 20px;
      display: inline-block;
      font-size: 1.5rem;
      font-weight: 700;
    }
    a:hover {
      color: #CCC;
    }
    header {
      position: relative;
      top: 0;
      left: 0;
      right: 0;
      width: 100%;
      border-bottom: 3px outset #bbb;
      height: 80px;
      z-index: 11;
      background: #000;
      text-align: center;
    }
    footer {
      position: relative;
      bottom: 0;
      left: 0;
      right: 0;
      width: 100%;
      border-top: 3px outset #bbb;
      text-align: center;
      height: 80px;
      z-index: 11;
      background: #000;
      margin: 0 auto;
    }
    .content {
      width: 100%;
      height: 100%;
      margin: 0 auto;
      position: relative;
      padding: 20px;
    }
    .sec {
      width: 92%;
      height: auto;
      border: 5px ridge #999;
      border-radius: 12px;
      margin: 20px auto;
    }
  </style>
</head>
<body>
  <header>
    <nav id="top"><a href="#end">To End</a>
    </nav>
  </header>
  <section class="sec">
    <article class="content">
      <iframe src='http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_eff_animate_smoothscroll' scrolling='no' frameborder='0' width='100%'></iframe>
    </article>
  </section>
  <main id='main'>
    <article class="content">
      "'I had NOT!' cried the Mouse, sharply and very angrily. 'A knot!' said Alice, always ready to make herself useful, and looking anxiously about her. 'Oh, do let me help to undo it!' 'I shall do nothing of the sort,' said the Mouse, getting up and walking
      away. 'You insult me by talking such nonsense!' 'I didn't mean it!' pleaded poor Alice. 'But you're so easily offended, you know!' The Mouse only growled in reply. 'Please come back and finish your story!'
    </article>
    <article class="content">
      Alice called after it; and the others all joined in chorus, 'Yes, please do!' but the Mouse only shook its head impatiently, and walked a little quicker. 'What a pity it wouldn't stay!' sighed the Lory, as soon as it was quite out of sight; and an old
      Crab took the opportunity of saying to her daughter 'Ah, my dear! Let this be a lesson to you never to lose YOUR temper!' 'Hold your tongue, Ma!' said the young Crab, a little snappishly. 'You're enough to try the patience of an oyster!' 'I wish
      I had our Dinah here, I know I do!' said Alice aloud, addressing nobody in particular.
    </article>
    <article class="content">
      'She'd soon fetch it back!' 'And who is Dinah, if I might venture to ask the question?' said the Lory. Alice replied eagerly, for she was always ready to talk about her pet: 'Dinah's our cat. And she's such a capital one for catching mice you can't think!
      And oh, I wish you could see her after the birds! Why, she'll eat a little bird as soon as look at it!' This speech caused a remarkable sensation among the party. Some of the birds hurried off at once: one old Magpie began wrapping itself up very
      carefully, remarking, 'I really must be getting home; the night-air doesn't suit my throat!' and a Canary called out in a trembling voice to its children, 'Come away, my dears! It's high time you were all in bed!'"
    </article>
    <article class="content">
      "Death!" I shouted. "Death is coming! Death!" and leaving him to digest that if he could, I hurried on after the artillery-man. At the corner I looked back. The soldier had left him, and he was still standing by his box, with the pots of orchids on the
      lid of it, and staring vaguely over the trees. No one in Weybridge could tell us where the headquarters were established; the whole place was in such confusion as I had never seen in any town before. Carts, carriages everywhere, the most astonishing
      miscellany of conveyances and horseflesh. The respectable inhabitants of the place, men in golf and boating costumes, wives prettily dressed, were packing, river-side loafers energetically helping, children excited, and, for the most part, highly
      delighted at this astonishing variation of their Sunday experiences. In the midst of it all the worthy vicar was very pluckily holding an early celebration, and his bell was jangling out above the excitement.
    </article>
    <article class="content">
      I and the artilleryman, seated on the step of the drinking fountain, made a very passable meal upon what we had brought with us. Patrols of soldiers--here no longer hussars, but grenadiers in white--were warning people to move now or to take refuge in
      their cellars as soon as the firing began. We saw as we crossed the railway bridge that a growing crowd of people had assembled in and about the railway station, and the swarming platform was piled with boxes and packages. The ordinary traffic had
      been stopped, I believe, in order to allow of the passage of troops and guns to Chertsey, and I have heard since that a savage struggle occurred for places in the special trains that were put on at a later hour.
    </article>
    <article class="content">
      We remained at Weybridge until midday, and at that hour we found ourselves at the place near Shepperton Lock where the Wey and Thames join. Part of the time we spent helping two old women to pack a little cart. The Wey has a treble mouth, and at this
      point boats are to be hired, and there was a ferry across the river. On the Shepperton side was an inn with a lawn, and beyond that the tower of Shepperton Church--it has been replaced by a spire--rose above the trees. Here we found an excited and
      noisy crowd of fugitives. As yet the flight had not grown to a panic, but there were already far more people than all the boats going to and fro could enable to cross. People came panting along under heavy burdens; one husband
    </article>
  </main>
  <section class="sec">
    <article class="content">
      <img src='https://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png'>
    </article>
  </section>
  <footer>
    <nav id="end"><a href="#top">To Top</a>
    </nav>
  </footer>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
      //Delagate: click event to all anchors
      $("a").on('click', function(event) {
        //Condition: If this anchor has "href=#" then...
        if (this.hash !== "") {
          //Inhibit: Default behavior of anchor
          event.preventDefault();
          //Store anchor's "#"
          var hash = this.hash;
          /*
          ||Target the root and parent of page content.
          ||.animate() scrolling from clicked anchor to
          ||location designated by the anchor's hash.
          */
          $('html, body').animate({
            scrollTop: $(hash).offset().top
          }, 800, function() {
            //return anchor behavior to anchor
            window.location.hash = hash;
          });
        }
      });
    });
  </script>
</body>
</html>