Javascript 如何滚动列表到顶部按钮点击角度?
你能告诉我如何将列表滚动到顶部按钮点击角度吗? 我试过这样做Javascript 如何滚动列表到顶部按钮点击角度?,javascript,angular,Javascript,Angular,你能告诉我如何将列表滚动到顶部按钮点击角度吗? 我试过这样做 scrollToTop(el){ el.scrollIntoView(); } <button (click)="scrollToTop(target)">scroll to top</button> scrollToTop(el){ el.scrollIntoView(); } 滚动到顶部 它将列表滚动到顶部。但是它隐藏了我的地址栏,然后用户无法看到标题。我认为这不是一个好的解决方案。
scrollToTop(el){
el.scrollIntoView();
}
<button (click)="scrollToTop(target)">scroll to top</button>
scrollToTop(el){
el.scrollIntoView();
}
滚动到顶部
它将列表滚动到顶部。但是它隐藏了我的地址栏
,然后用户无法看到标题
。我认为这不是一个好的解决方案。有人有其他好的解决方案吗
这是我的密码
通过将容器的
scrollTop
属性设置为零,可以滚动到列表顶部。请参见演示
<div #container class="container">
<ul>
<li *ngFor="let i of items">{{i}}</li>
</ul>
</div>
<button (click)="container.scrollTop = 0">scroll to top</button>
将
滚动
添加到容器中,使其在容器上工作,而不是在ul
app.component.html
<div class="container" #container>
<ul #target>
<li *ngFor="let i of items">{{i}}</li>
</ul>
</div>
<button (click)="scrollToTop(container)">scroll to top</button>
对于平滑滚动,请使用以下命令:
scrollToTop(el) {
var to = 0;
var duration = 1000;
var start = el.scrollTop,
change = to - start,
currentTime = 0,
increment = 20;
var easeInOutQuad = function(t, b, c, d) {
t /= d / 2;
if (t < 1)
return c / 2 * t * t + b;
t--;
return -c / 2 * (t * (t - 2) - 1) + b;
}
var animateScroll = function() {
currentTime += increment;
var val = easeInOutQuad(currentTime, start, change, duration);
el.scrollTop = val;
if(currentTime < duration) {
setTimeout(animateScroll, increment);
}
}
animateScroll();
}
scrollToTop(el){
var-to=0;
var持续时间=1000;
var start=el.scrollTop,
改变=开始,
currentTime=0,
增量=20;
var easeInOutQuad=函数(t,b,c,d){
t/=d/2;
if(t<1)
返回c/2*t*t+b;
t--;
返回-c/2*(t*(t-2)-1)+b;
}
var animateScroll=函数(){
当前时间+=增量;
var val=easeInOutQuad(当前时间、开始、更改、持续时间);
el.scrollTop=val;
如果(当前时间<持续时间){
设置超时(动画滚动,增量);
}
}
动画滚动();
}
示例,正如我们在jquery
中所做的那样,给出持续时间
来完成这项任务。目前它会快速移动到顶部。我们能否给出持续时间可以在中找到一些使用纯Javascript平滑滚动的代码。我添加了一种基于观察值的平滑滚动方法。
<div class="container" #container>
<ul #target>
<li *ngFor="let i of items">{{i}}</li>
</ul>
</div>
<button (click)="scrollToTop(container)">scroll to top</button>
scrollToTop(el) {
el.scrollTop = 0;
}
scrollToTop(el) {
var to = 0;
var duration = 1000;
var start = el.scrollTop,
change = to - start,
currentTime = 0,
increment = 20;
var easeInOutQuad = function(t, b, c, d) {
t /= d / 2;
if (t < 1)
return c / 2 * t * t + b;
t--;
return -c / 2 * (t * (t - 2) - 1) + b;
}
var animateScroll = function() {
currentTime += increment;
var val = easeInOutQuad(currentTime, start, change, duration);
el.scrollTop = val;
if(currentTime < duration) {
setTimeout(animateScroll, increment);
}
}
animateScroll();
}