仅使用纯 css 平滑滚动

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22246796/
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-30 02:02:37  来源:igfitidea点击:

Smooth scrolling with just pure css

css

提问by Youssef

How can I make a smooth scrolling with just pure css.

如何仅使用纯 css 进行平滑滚动。

I have this code Fiddle

我有这个代码小提琴

HTML

HTML

<a id="up" href="#down">down</a>
<div class="up"></div>

<a id="down" href="#up">up</a>
<div class="down"></div>

CSS

CSS

.up {
    width:100px;
    height: 600px;
    background-color: red;
}

.down {
    width:100px;
    height: 400px;
    background-color: yellow;
}

I know :targetcan help but I don't know how to use it with transition.

我知道:target可以提供帮助,但我不知道如何将它与transition.

采纳答案by SW4

You cando this with pure CSS but you will need to hard code the offset scroll amounts, which may not be ideal should you be changing page content- or should dimensions of your content change on say window resize.

可以使用纯 CSS 执行此操作,但您需要对偏移滚动量进行硬编码,如果您更改页面内容,或者您​​的内容尺寸在调整窗口大小时发生变化,这可能并不理想。

You're likely best placed to use e.g. jQuery, specifically:

您可能最适合使用例如 jQuery,特别是:

$('html, body').stop().animate({
   scrollTop: element.offset().top
}, 1000);

A complete implementation may be:

一个完整的实现可能是:

$('#up, #down').on('click', function(e){
    e.preventDefault();
    var target= $(this).get(0).id == 'up' ? $('#down') : $('#up');
    $('html, body').stop().animate({
       scrollTop: target.offset().top
    }, 1000);
});

Where elementis the target element to scroll to and 1000is the delay in ms before completion.

element要滚动到的目标元素在哪里,以及1000完成前的延迟(以毫秒为单位)。

Demo Fiddle

演示小提琴

The benefit being, no matter what changes to your content dimensions, the function will not need to be altered.

好处是,无论您的内容维度有什么变化,都不需要更改功能。

回答by sidney

You need to use the targetselector.

您需要使用target选择器。

Here is a fiddle with another example: http://jsfiddle.net/YYPKM/3/

这是另一个例子的小提琴:http: //jsfiddle.net/YYPKM/3/