javascript 如何更改网站上的滚动行为(例如速度、加速度)?

2guxujil  于 2023-03-11  发布在  Java
关注(0)|答案(5)|浏览(181)

网站上修改过的滚动行为是如何产生的?我想实现一个加速滚动行为,就像你在例子中看到的那样。所以你以一定的速度滚动,当你放开后,页面会自动滚动一点,速度变慢,然后停止。
很遗憾我完全没有基础给你提供代码,希望你还能帮助我。也许你能推荐一些js插件给我?
https://p2mv.studio/case/sony-music-france

des4xlb0

des4xlb01#

有两种方法可以实现这一点。可以使用CSS

html { scroll-behavior: smooth; }

也可以使用JavaScript:

// 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' 
});

// Scroll to a certain element
document.querySelector('.hello').scrollIntoView({ 
  behavior: 'smooth' 
})

您可以在这里阅读更多内容并找到更多示例:https://css-tricks.com/snippets/jquery/smooth-scrolling/

1l5u6lss

1l5u6lss2#

你可以试试这个:Nicescroll jQuery Plugin .
此库实现加速滚动。下载并导入脚本,然后添加以下内容:

$("body").niceScroll();
zrfyljdw

zrfyljdw3#

使用jQuery从按钮(class=“to-id”)滚动到标题(id=“myID”)。

<input class="to-id" name="contact_owner" value="Contact" />

<h1 id="myID">

<!-- scroll to ID -->
<script>            
    jQuery(document).ready(function() {
    
        jQuery('.to-id').click(function(event) {
            event.preventDefault();
            $('html, body').animate({scrollTop:$('#myID').position().top}, 1000);
            return false;
        })
    });
</script>
arknldoa

arknldoa4#

您可以使用CSS将scroll-behavior: smooth;应用于您希望平滑滚动行为的容器。
您可以通过向容器中的子元素添加过渡来进一步控制滚动的速度。如果您使用Javascript来控制子元素的位置,则只需添加一个过渡,例如transition: left 1s;,其中left是要过渡的CSS属性,1s是以秒为单位的时间。

bvjveswy

bvjveswy5#

您可以使用jquery简单地完成此操作。
css属性实际上导致了延迟,所以你可以用它来调整延迟。

transition-duration: 500ms;

参考:
transition-duration CSS属性设置完成过渡动画所需的时间长度。默认情况下,该值为0 s,表示不会出现动画。
x一个一个一个一个x一个一个二个一个x一个一个三个一个

相关问题