对于javascript中的循环不单独执行每个命令(如何停止它?) [英] For loop in javascript not performing each command individually ( how to stop it? )

查看:72
本文介绍了对于javascript中的循环不单独执行每个命令(如何停止它?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的html中,我有一个按钮形式的锚点链接:

In my html I have an anchor link in the form of a button:

<button><a href="#content">Go To Content</a></button>



链接到我的#content div。不幸的是,跳转到#content div是非常突然和严厉的。所以我尝试使用window.scrollTo()方法用Java Script动画它(是的,我想用纯粹的java脚本,甚至不是JQuery来做这个。)



要做到这一点,我想将整个滚动动作分成更小的部分;让每一个都比前面的那个长一点,以实现你在css中轻松获得的那种动画。



到目前为止,你会发现我的JS在代码中。代码运行时单击以进行测试。



这个问题出在smoothScroll函数的for循环中。似乎for循环只执行一次scroll命令然后忽略它。



如果你想要一个特定的问题:window.scroll函数只运行一次吗?与浏览器的速度相比,它的速度是否有限?应该有更好的方法来做我上面描述的吗?



我正在使用谷歌浏览器开发这个网站,只有纯Java脚本,Windows 10。



我不会发布我的HTML,所以问题不会太长。如果你想要我,请评论如此。



编辑:

@


which links to my #content div. Unfortunately the jump to the #content div is very sudden and harsh. So I tried animating it with Java Script by using the window.scrollTo() method ( And yes, I want to do this with ONLY pure java script, not even JQuery).

To do this I want to separate the whole scroll motion into smaller parts; making each one take a little bit longer than the one before it, to achieve the kind of animation you get with ease in css.

So far, you'll find my JS in the code. The code runs on click for testing purposes.

The issue with this is in the for loop in the smoothScroll function. It seems that the for loop executes the scroll command only once and then ignores it.

If you want a specific question: Does the window.scroll function run only once? Is it's speed limited someway in comparison to the speed of the browser? Should there be a better way of doing what I described above?

I'm developing this website with google chrome and ONLY pure Java Script, windows 10.

I won't post my html so the question doesn't get too long. If you want me to, please comment so.


@

Sinisa Hajnal 

有一点。循环只会累加滚动并在最后执行。因此,如果我有循环运行8次并每次滚动10个像素,它将不会单独执行,它只会滚动一次。



有谁知道如何停止这个?



我尝试了什么:



has a point. The loop just adds up the scrolling and performs it at the end. So if I have the loop run 8 times and scroll 10 pixels each time, it wouldn't do it individually, it would just scroll once.

Does anyone know how to stop this?

What I have tried:

function smoothScroll(){
  for (i = 0; i < 80; i+=10 ){
        sleep(10)
        window.scrollTo(0, i)
    }
 }
// here we run our function when the user clicks on the webpage
window.onclick = function(){
    smoothScroll()
}

推荐答案

它比一个简单的循环要复杂一点(记住JS本质上是单线程的)...

如何在Vanilla JavaScript中实现平滑滚动 - SitePoint [ ^ ]
It is a bit more complicated, than a simple loop (remember JS is single threaded by nature)...
How to Implement Smooth Scrolling in Vanilla JavaScript — SitePoint[^]


这篇关于对于javascript中的循环不单独执行每个命令(如何停止它?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆