平滑滚动与纯CSS [英] Smooth scrolling with just pure css
问题描述
如何使用纯CSS进行平滑滚动。
我有此代码 小提琴
HTML
< a id = uphref =#down>向下< / a>
< div class =up>< / div>
< a id =downhref =#up>向上< / a>
< div class =down>< / div>
CSS
.up {
width:100px;
height:600px;
background-color:red;
}
.down {
width:100px;
height:400px;
background-color:yellow;
}
我知道:target
可以帮助,但我不知道如何使用 transition
。
您可以使用纯CSS执行此操作,但您需要对偏移量滚动量进行硬编码,如果您更改页面内容,或者您的内容尺寸发生变化,这可能不太理想说窗口调整大小。
您最有可能使用eg jQuery,具体来说:
$('html,body')stop()。animate({
scrollTop: element.offset()。top
},1000);
完整的实现可能是:
$('#up,#down')。on('click',function(e){
e.preventDefault();
var target = $ this).get(0).id =='up'?$('#down'):$('#up');
$('html,body')。stop {
scrollTop:target.offset()。top
},1000);
});
其中元素
是要滚动的目标元素到 1000
是完成前的延迟(ms)。
演示小提琴
无论您的内容尺寸有什么变化,该函数将不需要更改。
How can I make a smooth scrolling with just pure css.
I have this code Fiddle
HTML
<a id="up" href="#down">down</a>
<div class="up"></div>
<a id="down" href="#up">up</a>
<div class="down"></div>
CSS
.up {
width:100px;
height: 600px;
background-color: red;
}
.down {
width:100px;
height: 400px;
background-color: yellow;
}
I know :target
can help but I don't know how to use it with transition
.
You can do 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.
You're likely best placed to use e.g. jQuery, specifically:
$('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 element
is the target element to scroll to and 1000
is the delay in ms before completion.
Demo Fiddle
The benefit being, no matter what changes to your content dimensions, the function will not need to be altered.
这篇关于平滑滚动与纯CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!