简体   繁体   English

使用 scrollIntoView 实现 JavaScript 平滑滚动效果

[英]JavaScript Smooth Scrolling effect with scrollIntoView

Okay, I am attempting to get a single page (two divs), Primarily a splash screen, which when you click 'Enter site' and it will scroll down smoothly to the 'main site', However it jumps to it, rather than smooth scrolling to the element.好的,我正在尝试获取一个页面(两个 div),主要是一个启动画面,当您单击“进入站点”时,它将平滑地向下滚动到“主站点”,但是它会跳转到它,而不是平滑滚动到元素。

How would can I get it to scroll to that element smoothly without this jump effect?如果没有这种跳跃效果,我怎样才能让它平滑地滚动到那个元素?

Here is my a snippet:这是我的一个片段:

 splash = document.getElementById('intro'); content = document.getElementById('content'); function enterSite() { content.scrollIntoView({ behaviour: "smooth" }); }
 body { font-family: 'Archivo Narrow', sans-serif; margin: 0 auto; width: 100%; height: 100%; } html, body { overflow: hidden; } main { width: 100%; height: 100%; position: relative; } #intro { background-image: url(https://i.imgsafe.org/51d0cf26df.jpg); background-repeat: no-repeat; background-size: cover; display: flex; text-align: center; height: 100%; } #splash { margin: auto; width: 40%; background-color: rgba(56, 56, 56, 0.4); border-radius: 50px 50px; } #splash-p { width: 70%; font-size: 1.2em; line-height: 1.5em; margin: auto; text-align: center; padding-top: 10px; color: #fff; } .btn { width: 35%; margin: auto; margin-top: 10px; margin-bottom: 10px; } /* Main Content Page */ article { position: absolute; width: 100%; height: 100%; background-color: red; }
 <div id="intro"> <div id="splash"> <p id="splash-p">Just a load of text repeated</p> <input type="image" src="Images/Button.png" class="btn" onclick="enterSite()" /> </div> </div> <article id="content">Just a load of text repeated</article>

If you click the button it will jump to the next div, but i need it to scroll smoothly rather than jump to the next div, Using pure javascript, everywhere else i have looked seems to have plug ins or uses jquery.如果您单击按钮,它将跳转到下一个 div,但我需要它平滑滚动而不是跳转到下一个 div,使用纯 javascript,我看过的其他地方似乎都有插件或使用 jquery。

If you don't want a straight jump, you should animate the scroll somehow.如果你不想直接跳跃,你应该以某种方式为滚动设置动画。
With the help of jQuery is easy as that:在 jQuery 的帮助下,这很容易:

$("html, body").animate({ scrollTop: $([ELEMENT]).position().top }, 1000);

Look at this fiddle: https://jsfiddle.net/8501ckvn/看看这个小提琴: https : //jsfiddle.net/8501ckvn/


jQuery solves a lot of cross browser issues, but if you are looking for a pure javascript solution there are already many answers on Stackoverflow, ie look at Smooth scroll anchor links WITHOUT jQuery . jQuery 解决了很多跨浏览器问题,但如果您正在寻找纯 javascript解决方案,Stackoverflow 上已经有很多答案,即查看Smooth scroll anchor links WITHOUT jQuery

Your content.scrollIntoView({behaviour: "smooth"});你的content.scrollIntoView({behaviour: "smooth"}); should work, however, I think 'behaviour' is spelt behavior .应该有效,但是,我认为“行为”是拼写行为

I did develop a way of smooth scrolling with TypeScript, but you should be able to convert to JS quite easily:我确实开发了一种使用 TypeScript 平滑滚动的方法,但是您应该能够很容易地转换为 JS:

View stackoverflow answer 查看 stackoverflow 答案

For a more comprehensive list of methods for smooth scrolling, see my answer here .对于用于平滑滚动的方法更全面的列表,请参阅我的答案在这里


To scroll to a certain position in an exact amount of time, window.requestAnimationFrame can be put to use, calculating the appropriate current position each time.要在精确的时间内滚动到某个位置,可以使用window.requestAnimationFrame ,每次计算适当的当前位置。 setTimeout can be used to a similar effect when requestAnimationFrame is not supported.当不支持requestAnimationFrame时,可以使用setTimeout达到类似的效果。

/*
   @param pos: the y-position to scroll to (in pixels)
   @param time: the exact amount of time the scrolling will take (in milliseconds)
*/
function scrollToSmoothly(pos, time) {
    var currentPos = window.pageYOffset;
    var start = null;
    if(time == null) time = 500;
    pos = +pos, time = +time;
    window.requestAnimationFrame(function step(currentTime) {
        start = !start ? currentTime : start;
        var progress = currentTime - start;
        if (currentPos < pos) {
            window.scrollTo(0, ((pos - currentPos) * progress / time) + currentPos);
        } else {
            window.scrollTo(0, currentPos - ((currentPos - pos) * progress / time));
        }
        if (progress < time) {
            window.requestAnimationFrame(step);
        } else {
            window.scrollTo(0, pos);
        }
    });
}

Demo:演示:

 function scrollToSmoothly(pos, time) { var currentPos = window.pageYOffset; var start = null; if(time == null) time = 500; pos = +pos, time = +time; window.requestAnimationFrame(function step(currentTime) { start = !start ? currentTime : start; var progress = currentTime - start; if (currentPos < pos) { window.scrollTo(0, ((pos - currentPos) * progress / time) + currentPos); } else { window.scrollTo(0, currentPos - ((currentPos - pos) * progress / time)); } if (progress < time) { window.requestAnimationFrame(step); } else { window.scrollTo(0, pos); } }); } document.getElementById("toElement").addEventListener('click', function(e) { var elem = document.querySelector("div"); scrollToSmoothly(elem.offsetTop); }); document.getElementById("toTop").addEventListener('click', function(e){ scrollToSmoothly(0, 700); });
 <button id="toElement">Scroll To Element</button> <div style="margin: 1000px 0px; text-align: center;">Div element <button id="toTop">Scroll back to top</button> </div>

For more complex cases, the SmoothScroll.js library can be used, which handles smooth scrolling both vertically and horizontally, scrolling inside other container elements, different easing behaviors, scrolling relatively from the current position, and more.对于更复杂的情况,可以使用SmoothScroll.js 库,它处理垂直和水平平滑滚动、在其他容器元素内部滚动、不同的缓动行为、从当前位置相对滚动等等。

 document.getElementById("toElement").addEventListener('click', function(e) { smoothScroll({toElement: document.querySelector('div'), duration: 500}); }); document.getElementById("toTop").addEventListener('click', function(e){ smoothScroll({yPos: 0, duration: 700}); });
 <script src="https://cdn.jsdelivr.net/gh/LieutenantPeacock/SmoothScroll@1.2.0/src/smoothscroll.min.js" integrity="sha384-UdJHYJK9eDBy7vML0TvJGlCpvrJhCuOPGTc7tHbA+jHEgCgjWpPbmMvmd/2bzdXU" crossorigin="anonymous"></script> <button id="toElement">Scroll To Element</button> <div style="margin: 1000px 0px; text-align: center;">Div element <button id="toTop">Scroll back to top</button> </div>

Alternatively, you can pass an options object to window.scroll which scrolls to a specific x and y position and window.scrollBy which scrolls a certain amount from the current position:或者,您可以将选项对象传递给window.scroll ,它滚动到特定的 x 和 y 位置,以及window.scrollBy从当前位置滚动一定量:

// Scroll to specific values
// scrollTo is the same
window.scroll({
  top: 2500, 
  left: 0, 
  behavior: 'smooth' 
});

// Scroll certain amounts from current position 
window.scrollBy({ 
  top: 100, // could be negative value
  left: 0, 
  behavior: 'smooth' 
});

Demo:演示:

 <button onClick="scrollToDiv()">Scroll To Element</button> <div style="margin: 500px 0px;">Div</div> <script> function scrollToDiv(){ var elem = document.querySelector("div"); window.scroll({ top: elem.offsetTop, left: 0, behavior: 'smooth' }); } </script>

Modern browsers support the scroll-behavior CSS property , which can be used to make scrolling in the document smooth (without the need for JavaScript).现代浏览器支持scroll-behavior CSS 属性,可用于使文档中的滚动平滑(无需 JavaScript)。 Anchor tags can be used for this by giving the anchor tag a href of # plus the id of the element to scroll to).锚标签可用于此目的,方法是为锚标签提供#href加上要滚动到的元素的id )。 You can also set the scroll-behavior property for a specific container like a div to make its contents scroll smoothly.您还可以为特定容器(如div设置scroll-behavior属性,以使其内容平滑滚动。

Demo:演示:

 html, body{ scroll-behavior: smooth; }
 <a href="#elem">Scroll To Element</a> <div id="elem" style="margin: 500px 0px;">Div</div>

Assuming that you have JQuery as well.假设您也有 JQuery。

You could make use of the following JQuery code to get a smooth scrolling effect您可以使用以下 JQuery 代码来获得平滑的滚动效果

function enterSite(){
    $('html, body').stop().animate({
        scrollTop: $('#content').offset().top
    }, 1500);
});

Let me know if it worked让我知道它是否有效

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM