平滑幻灯片在javascript中如何工作? [英] How do smooth slides work in javascript?

查看:56
本文介绍了平滑幻灯片在javascript中如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一段时间以来,我一直在尝试找出JavaScript中平滑幻灯片,淡入淡出等背后的算法.举例来说,我看到一个div的内容高度为0px并被切换,它不仅将 snap 调整为高度,而且平滑且通过某种功能逐渐发展到高度.我所知道的是,这个div的高度是从具有间隔集或某种循环的日期对象中分配的高度值.我在网上搜索了所有内容,试图找到说明其工作原理的教程,但均失败了.有人可以向我解释如何创建自己的平滑渐变,幻灯片或引用一些我可以阅读的链接吗?

For a while now i have been trying to figure out the algorithms behind smooth slides, fades etc..in javascript. Just to give you an example of what am talking about, I have seen a div with content in it that had a height of 0px and on toggled, it didn't just snap to height, it smoothly and gradually grew to height using some sort of function. What i do know is that the height of this div was being assigned its height value from either a date object that had an interval set or a loop of some sort. I've searched all over the web trying to find tutorials explaining how this works but failed. Can someone please either explain to me how to create my own smooth fades, slides or reference some links that i can read?

PS:我知道我只能使用jquery,但我想知道淡入淡出和滑动的实际作用.

推荐答案

实际上很简单.所有这些动画都使用一个间隔很短的计时器(请参见 setInterval ),例如100毫秒,并且每当计时器启动时,属性(高度或其他任何东西)都会更改为总数的一小部分,而不是一次全部更改.

It's quite simple actually. All of these animations use a timer (see setInterval) with a short interval, say 100 milliseconds, and every time the timer fires, the property (height or whatever) is changed by a fraction of the total amount instead of all at once.

例如,如果您想在1秒内从0px的高度滑动到200px,则可以设置一个计时器,该计时器每100 ms触发一次,并将DIV的高度增加20px.这样一来,计时器将在1秒内触发10次,并且高度将为200px.

For example, if you want to slide from a height of 0px to 200px in 1 second, then you could set up a timer that fires every 100 ms and increases the height of the DIV by 20px. That way, in 1 second, the timer would have fired 10 times and the height would be 200px.

一个简单的例子:

function slideOpen(elem, finalHeight, slideTime) {
  var count = slideTime * 10;      // 10 intervals per second
      height = 0,                  // current height
      delta = finalHeight / count; // change in height per interval

  var timerId = setInterval(slide, 100);

  function slide() {
    height += delta;
    elem.style.height = height + 'px';
    if (--count == 0)
      clearInterval(timerId);
  }
}

这篇关于平滑幻灯片在javascript中如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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