.stop()&。animate()jQuery函数转换为javascript

我也想学习JavaScript。 并将各种jQuery函数看作等效的JavaScript。

我想将此jQuery函数转换为其等效的JavaScript函数? 我怎样才能做到这一点?

$('.sample').stop().animate({ left: '-102px' }, 1000); 

简而言之,jQuery动画是一个定期计时器,可以在每个计时器滴答中更改一个或多个CSS属性。

此外,jQuery实现了一个补间算法,该算法在每个计时器时间点计算动画是在前面还是落后于计划并进行调整,以便动画始终在指定的确切时间内完成。

此外,jQuery实现了一个动画队列,以便可以将多个动画链接在一起(当前一个完成时启动下一个动画)。

此外,jQuery还支持缓动函数,允许您根据特定算法指定非线性动画,以便在此期间改变速度。

仅供参考,如果您需要更多详细信息,jQuery javascript源代码完全可用 。 这项工作的核心是一个名为doAnimation()的本地函数,尽管大部分工作都是在名为stepupdate函数中完成的,可以在jQuery.fx.prototype的定义中找到。

这是另一个在纯javascript中显示简单淡入淡出动画的答案。

这是关于动画的一般教程 。

您可以在此处查看有关为动画使用计时器的讨论。

你可以在这里看到补间的讨论。

这是您特定动画的javascript版本:

 // node is the DOM element to animate // prop is the CSS property name to animate // end is the CSS value to animate to (only supports px units) // duration is the time of the animation in ms // fn is an optional callback when the animation is done // fn is called like this fn(node, arg) // arg is an optional argument that is passed to the callback // context is an optional argument that is the this pointer for the function function animate(node, prop, end, duration, fn, arg, context) { var stepTime = 20; var startTime = new Date().getTime(); var start = parseInt(getComputedStyle(node).getPropertyValue(prop), 10); if (typeof end === "string") { end = parseInt(end, 10); } function step() { // calc how much time has elapsed var nextValue, done, portionComplete; var timeRunning = new Date().getTime() - startTime; if (timeRunning >= duration) { nextValue = end; done = true; } else { portionComplete = timeRunning / duration; nextValue = ((end - start) * portionComplete) + start; done = false; } // set the next value node.style[prop] = nextValue + "px"; if (!done) { setTimeout(step, stepTime); } else { context = context || window; fn.call(context, node, arg); } } // start the animation step(); } 

工作演示: http : //jsfiddle.net/jfriend00/Mc3xD/


为了简化理解,这并没有实现jQuery示例的.stop()部分,因为这需要一个单独的数据结构来跟踪在给定对象上运行的每个动画计时器,这可以在更复杂的版本中看到支持stop() : http : //jsfiddle.net/jfriend00/mp4Yq/ 。

你提醒我,当我开始学习js,然后很高兴找到jquery,无论如何我不知道你为什么反过来,但回答你的问题

javascript中的动画可以使用setInterval函数使用,在很短的时间内(通常为24毫秒)更改top,left … etc属性,这对人眼来说就像一条流而不是像单独的位置一样,也是你可以考虑使用纯css3,但是可以使用这样的函数

  var position,ratio,time,mytimer; document.getElementById("hi").style.left=0; function animate_left(position,time) { ratio=position/time; if(parseInt(document.getElementById("hi").style.left)<=position) { document.getElementById("hi").style.left=(parseInt(document.getElementById("hi").style.left)+ratio*100).toString()+"px" } else { clearInterval(mytimer) } } function animate(value1,value2) { mytimer=setInterval(function(){animate_left(value1,value2)},10) //where 10 is minimum smooth animation factor for human eye } animate(600,1000); 

http://jsfiddle.net/prollygeek/er67f/6/