velocity.js_使用Velocity.js使您的网站具有互动性和乐趣(无需jQuery)

velocity.js

Get Up and Running with Velocity.js at Warp Speed (No jQuery)

Special thanks from me go to James Hibbard and the developers behind Velocity for reviewing this article. Also to users and developers who contribute and have contributed to Velocity over the years.

我要特别感谢James Hibbard和Velocity背后的开发人员对本文的审阅。 还要感谢多年来为Velocity做出贡献并做出贡献的用户和开发人员。

In this article I introduce Velocity.js, a fast and high-powered JavaScript animation engine by Julian Shapiro. By the time you go through all the demos, you’ll be able to use Velocity.js to create your own animations and make your website more interactive and user-friendly. All of this without using jQuery, just vanilla JavaScript.

在本文中,我介绍了Velocity.js,这是朱利安·夏皮罗(Julian Shapiro)提供的快速而强大JavaScript动画引擎。 在进行所有演示时,您将可以使用Velocity.js创建自己的动画并使网站更具交互性和用户友好性。 所有这些都无需使用jQuery,而只需使用普通JavaScript。

This is the third article in the series Beyond CSS: Dynamic DOM Animation Libraries.

这是“ 超越CSS:动态DOM动画库 ”系列中的第三篇文章。

Here’s what I have already covered:

这是我已经介绍的内容:

  • Animating the DOM with Anime.js touches on how best to use animation on the web and when you could consider using a JavaScript animation library instead of CSS-only animation. It then focuses on Anime.js, a free and lightweight JavaScript animation library

    使用Anime.js对DOM进行动画处理将介绍如何在网络上最好地使用动画,以及何时可以考虑使用JavaScript动画库而不是仅CSS动画。 然后重点介绍Anime.js,这是一个免费的轻量级JavaScript动画库

  • Fun Animation Effects with KUTE.js introduces you to KUTE.js, a free and feature-rich JavaScript animation library.

    带有KUTE.js的有趣动画效果向您介绍KUTE.js,这是一个免费的功能丰富JavaScript动画库。

您可以使用Velocity.js制作动画 (What You Can Animate with Velocity.js)

Velocity.js is a powerful library, which puts the DOM at your fingertips! It lets you animate:

Velocity.js是一个功能强大的库,使DOM触手可及! 它可以动画:

  • Numeric values of CSS animatable properties, including colors

    CSS动画属性的数值,包括颜色
  • Transforms

    变身
  • SVG properties

    SVG属性
  • Scroll events, both relative to the page or to a container element inside the page

    相对于页面或页面内部容器元素的滚动事件
  • Fade and slide animations.

    淡入淡出和幻灯片动画。

In general, Velocity animates one numeric property value at a time. For instance, if you want to translate an element along both X and Y coordinates, you can’t use something like translate['10px', '15px']. Rather, you should accompany the translate property with its corresponding axis, like this: translateX: '10px', translateY: '15px'. There is one feature called forcefeeding, which Velocity makes available to let you specify two values at the same time. I’m going to introduce forcefeeding later in this article.

通常,Velocity一次为一个数字属性值设置动画。 例如,如果要同时沿X和Y坐标平移元素,则不能使用诸如translate['10px', '15px'] 。 相反,您应该将translate属性与其相应的轴一起使用,如下所示: translateX: '10px', translateY: '15px' 。 有一项功能称为forcefeeding ,Velocity可让您同时指定两个值。 我将在本文后面介绍强制进给。

选件 (Options)

Velocity’s options object gives you quite a bit of flexibility in crafting your animations.

Velocity的options对象使您在制作动画时具有很大的灵活性。

Here’s a list of the options you’ll see in the demos for this article:

这是您将在本文的演示中看到的选项列表:

  • Duration: how long each animation lasts. The unit of measurement for duration is milliseconds

    持续时间 :每个动画持续多长时间。 持续时间的度量单位是毫秒

  • Easing: Velocity supports most jQuery UI easing types, CSS3 easings, i.e., “ease”, “ease-in”, “ease-out”, and “ease-in-out”, bezier curves, step easing, and even cool spring physics. You can play with this demo to see the spring physics option in action

    缓动 :Velocity支持大多数jQuery UI缓动类型,CSS3缓动,即“缓动”,“缓入”,“缓动”和“缓入”,贝塞尔曲线,阶梯缓动,甚至是凉爽的弹簧物理。 您可以播放此演示,以查看实际的“弹簧物理”选项

  • Loop: how many times the animation should be repeated. If you set this option to true, it will run indefinitely

    循环 :动画应重复多少次。 如果将此选项设置为true ,它将无限期运行

  • Delay: how long to wait before the start of an animation.

    延迟 :动画开始前要等待多长时间。

A full list of options, is available on Velocity’s docs page.

Velocity的docs页面上提供了选项的完整列表。

句法 (Syntax)

If you’re a jQuery user, Velocity.js makes things easy for you. In fact, Velocity has the same API as jQuery. To get started:

如果您是jQuery用户,则Velocity.js可让您轻松完成工作。 实际上,Velocity具有与jQuery相同的API。 开始:

Download Velocity, include it on your page, and replace all instances of jQuery’s $.animate() with $.velocity().

下载速度,包括它在网页上,并更换jQuery的所有实例$.animate()$.velocity()

Velocity.js Docs

Velocity.js文件

However, you don’t need jQuery to work with Velocity, and you are not going to use jQuery for the demos in this article. The syntax will be a bit different from what you would use if jQuery were included. Here’s what it looks like:

但是,您不需要jQuery即可使用Velocity,并且您不会在本文的演示中使用jQuery。 语法将与包含jQuery时使用的语法有所不同。 看起来是这样的:

Velocity(element, {property: value}, {option: optionValue});

To chain another animation on the same element, just add another Velocity call after the previous one:

要将另一个动画链接到同一元素上,只需在上一个动画之后添加另一个Velocity调用即可:

Velocity(element1, {property: value}, {option: optionValue});
Velocity(element1, {property: value}, {option: optionValue});

To apply an animation to multiple elements at the same time, just cache all of the elements into a variable and call Velocity on that variable, no need to write your own loop. For instance:

要将动画同时应用于多个元素,只需将所有元素缓存到一个变量中,然后对该变量调用Velocity,而无需编写自己的循环。 例如:

const elements = document.querySelectorAll('<div>');
Velocity(elements, {property: value}, {option: optionValue});

You can use px, %, rem, em, vw/vh and deg. If you don’t add a unit, Velocity assumes an appropriate unit for you, usually px.

您可以使用px%rememvw/vhdeg 。 如果您不添加单位,则Velocity会为您假设一个合适的单位,通常为px

Velocity also supports operations with +, , * and /, as well as relative math operations by adding an equal (=) sign after each operator, e.g., '+=3em'

Velocity还支持通过+*/进行的运算以及相对数学运算,方法是在每个运算符之后添加一个等号( = ),例如'+=3em'

Velocity.js强制进给:传递初始值 (Velocity.js Forcefeeding: Passing Initial Values)

Instead of letting Velocity.js query the DOM to get an element’s initial value, you can set it yourself using this syntax:

您可以使用以下语法自行设置它,而不是让Velocity.js查询DOM来获取元素的初始值:

Velocity(element, {
  translateX: [endValue, startValue],
  backgroundColor: [endValue, easing, startValue]
}, {
  //options here
});

In this case, you pass an array of two, optionally three, items:

在这种情况下,您传递了两个(可选为三个)项目的数组:

  • The first item is a value for the final state of your animation

    第一项是动画最终状态的值

  • The second, optional, item is an easing option applied to that specific property

    第二个可选项是应用于该特定属性的缓动选项

  • The starting state of your tween, that is, the values you explicitly set for that specific property at the beginning of the animation, is the the last item in the array.

    补间的开始状态 ,即您在动画开始时为该特定属性显式设置的值,是数组中的最后一项

You can read more on forcefeeding on Velocity’s docs.

您可以在Velocity的docs上阅读有关强制进给更多信息。

控制Velocity.js动画 (Taking Control of Velocity.js Animations)

You can stop, pause, reverse and resume all Velocity calls on an element using this syntax:

您可以使用以下语法停止,暂停,撤消和恢复元素上的​​所有Velocity调用:

  • To stop: Velocity(elem, 'stop');

    停止: Velocity(elem, 'stop');

  • To pause: Velocity(elem, 'pause');

    暂停: Velocity(elem, 'pause');

  • To reverse: Velocity(elem, 'reverse');

    反转: Velocity(elem, 'reverse');

  • To resume: Velocity(elem, 'resume');

    恢复: Velocity(elem, 'resume');

Armed with these basic instructions, you can start diving into some practical examples.

掌握了这些基本说明后,您就可以开始研究一些实际示例了。

演示:落球 (Demo: Falling Ball)

Start with a simple ball falling from the top of the page.

从页面顶部落下一个简单的球开始。

const ball = document.querySelector('.ball');

Velocity(ball, {
  translateY: '130px'
}, {
  easing: [1000, 20],
  duration: 2000
});

The code above selects an HTML element with the class of .ball, translates it 130px along the Y axis over 2 seconds (just for demonstration purposes, otherwise I recommend a much shorter duration) with a movement that accelerates as it falls and gets bouncy at the end.

上面的代码选择一个类为.ballHTML元素,并在2秒钟内沿Y轴将其平移130px(仅出于演示目的,否则我建议使用更短的持续时间),其运动会随着其下落而加速,并在结束。

You can quickly achieve this with Velocity spring physics as an array value for the easing option: the first array item represents tension, the second one represents friction. A high tension value increases total speed and bounciness (default is 500), a lower friction value increases the vibration speed at the end (default is 20).

您可以使用Velocity spring physics作为缓动选项的数组值快速实现此目的:第一个数组项表示拉力 ,第二个数组项表示摩擦力较高的张力值会增加总速度和弹性(默认值为500), 较低的摩擦值会增加最终的振动速度(默认值为20)。

For the fun of it, have the ball’s background color animate from an initial value of a bluish color to a dark color. To set the initial value for the background color, you need to use Velocity.js forcefeed:

有趣的是,使球的背景颜色从蓝色的初始值变为深色的动画。 要设置背景色的初始值,您需要使用Velocity.js forcefeed

Velocity(ball, {
  translateY: '130px',
  //array items: endValue, startValuebackgroundColor : ['#222', '#043d99']
}, {
  //options here
});

And that’s it for this basic implementation of Velocity.js. Have a play with the code below:

这就是Velocity.js的基本实现。 玩下面的代码:

See the Pen Simple falling ball with Velocity.js by SitePoint (@SitePoint) on CodePen.

请参阅CodePen带有 SitePoint( @SitePoint )的Velocity.js的Pen Simple下降球

演示:按钮控制的弹跳球 (Demo: Button-Controlled Bouncing Ball)

For the next demo, the goal is to create this animation sequence:

对于下一个演示,目标是创建此动画序列:

  • The ball falls from the top

    球从顶部掉落
  • It looks a bit squashed as it hits the ground

    撞到地面时看起来有点压扁
  • It gains its natural shape as it bounces back up

    弹起后会恢复其自然形状
  • This animation keeps going in a loop

    这个动画不断循环
  • You can stop and restart the looping animation at the click of a button.

    单击按钮即可停止并重新启动循环动画。

Achieving this kind of animation requires stringing together a number of tweens and controlling their animation as a whole using buttons.

要实现这种动画,需要将多个补间串联在一起,并使用按钮来整体控制其动​​画。

The ideal tool for this would be a timeline which would encompass all the tweens and make it possible to control when all of the tweens start and end. Velocity.js does not have a native timeline, but you have a couple of options:

理想的工具是一个时间线,该时间线将包含所有补间,并且可以控制所有补间的开始和结束时间。 Velocity.js没有本地时间轴,但是您有两个选择:

  • Using Tweene — this is an animation proxy, that is, a wrapper you can use with a number of JavaScript animation libraries, including Velocity.js. I’ve tried this route, but unfortunately, Tweene expects Velocity to work with jQuery, which is not the case here. Perhaps you can tweak Tweene’s code, but this is not ideal

    使用Tweene-这是一个动画代理 ,即可以与许多JavaScript动画库(包括Velocity.js)一起使用的包装器。 我已经尝试过这条路线,但不幸的是,Tweene希望Velocity可以与jQuery一起使用,在这里情况并非如此。 也许您可以调整Tweene的代码,但这并不理想

  • Resorting to JavaScript requestAnimationFrame(), which at the time of writing is supported in all major browsers except Opera Mini. This is a native API for running any kind of smooth, performant animation in the browser environment, e.g., CSS, canvas, etc., and it’s the approach you’ll be using here every time you need this kind of functionality.

    借助JavaScript requestAnimationFrame() ,在编写本文时,除Opera Mini以外的所有主要浏览器支持该功能 。 这是一个本机API,用于在浏览器环境中运行任何类型的平滑,高性能的动画,例如CSS,canvas等,这是每次需要这种功能时都会在这里使用的方法。

将补间分割为不同的功能 (Splitting Tweens into Different Functions)

To keep the code clean, you could build a function for the animation scenes you need. Then, you would just call these functions inside what I call a master function, which contains the requestAnimationFrame() method.

为了保持代码干净,您可以为所需的动画场景构建函数。 然后,您只需在我称为master函数 (包含requestAnimationFrame()方法requestAnimationFrame()内部调用这些函数。

Here’s the code:

这是代码:

const changeBallPosition = (elem, propVal, easingVal, durationVal) => {
  Velocity(elem, {
    translateY: propVal
  }, {
    easing: easingVal,
    duration: durationVal
  });
};

const changeBallWidth = (elem, propVal, easingVal, durationVal) => {
  Velocity(elem, {
    scaleX: propVal
  }, {
    easing: easingVal,
    duration: durationVal
  });
};

The snippet above contains examples of how to write ES6 arrow functions. You need to get rid of the keyword function and use a fat arrow symbol(=>) after parentheses instead.

上面的代码段包含有关如何编写ES6箭头函数的示例。 您需要摆脱关键字function并在括号后使用粗箭头符号( => )。

The function is stored in a constant using the const keyword. Without diving too deep, let’s say that you cannot update the value of constants. If you need to store a value that needs updating throughout your program, use let instead. To learn more, ES6 let VS const variables by Wes Bos is a great read.

的功能被存储在使用恒定的 const关键字。 如果不跳得太深,可以说您无法更新常量的值。 如果您需要存储需要在整个程序中进行更新的值,请使用let代替。 要了解更多信息, ES6让 Wes Bos的VS const变量读起来很棒。

As you can see, each function contains a Velocity call that causes the ball to perform a specific movement. Notice that to move the ball and change its width, the code doesn’t change CSS top and width property values respectively. Rather, it changes the values of the translate and scale properties, which bring about a much more performant animation.

如您所见,每个函数都包含一个Velocity调用,该调用使球执行特定的运动。 请注意,要移动球并更改其宽度,代码不会分别更改CSS topwidth属性值。 而是,它更改了translatescale属性的值,从而带来了性能更高的动画。

Here’s the master function with the timer. It’s here that you place a call to the functions above:

这是计时器的主要功能。 在这里,您可以调用上面的函数:

let animationFrameID;

const launchBall = (elem) => {
  changeBallPosition(elem, '130px', 'easeInQuart', 300);
  changeBallWidth(elem, 1.2, 'linear', 50);
  changeBallWidth(elem, 1, 'linear', 50);
  changeBallPosition(elem, '-10px', 'easeOutQuart', 300);
  changeBallWidth(elem, 1, 'linear', 50);
  animationFrameID = requestAnimationFrame(
    () => {
      launchBall(elem);
    });
};

Notice the global animationFrameID variable. You will need this variable to stop the animation with cancelAnimationFrame() later in the code, so hold on to it!

注意全局animationFrameID变量。 在代码的后面,您将需要此变量来使用cancelAnimationFrame()停止动画,所以请继续!

To set the ball in motion, handle the Play button’s click event by calling the launchBall() function and passing the ball argument to it:

要使球运动,请通过调用launchBall()函数并将ball参数传递给Play按钮来处理“ 播放”按钮的click事件:

btnPlay.addEventListener('click', function() {
  launchBall(ball);
  this.disabled = true;
  btnStop.disabled = false;
});

Notice how this time you use the function keyword to write the callback that handles the click event. This is so because you are using the this keyword to refer to the button that is being clicked i.e., this.disabled = true;. If you used an arrow function, the this keyword would refer to the global window object, which would cause an error and prevent you from achieving the desired result. In short, don’t use arrow functions in callback functions with dynamic context.

请注意,这一次您如何使用function关键字编写处理click事件的回调。 之所以如此,是因为您使用this关键字来引用被单击的按钮,即this.disabled = true; 。 如果使用箭头功能,则this关键字将引用全局window对象,这将导致错误并阻止您获得所需的结果。 简而言之,不要在带有动态上下文的回调函数中使用箭头函数。

Once the animation is triggered, you don’t need users to keep clicking on the Play button, so the next line of code disables it while also enabling the Stop button, so users can stop the animation at any time.

触发动画后,您不需要用户继续单击“ 播放”按钮,因此下一行代码将禁用它,同时启用“ 停止”按钮,因此用户可以随时停止动画。

To stop the ball, you need a new function:

要停球,您需要一个新功能:

const removeAnimFrame = () => {
  if (animationFrameID) {
    cancelAnimationFrame(animationFrameID);
  }
}

Here, you place the call to cancelAnimationFrame() by passing animationFrameID, which as you remember, contains a reference to the ball’s looping animation.

在这里,您通过传递animationFrameID 放置cancelAnimationFrame()调用 ,您还记得,该cancelAnimationFrame()包含对球的循环动画的引用。

Finally, this is how you would handle the Stop button’s click event:

最后,这是处理“ 停止”按钮的click事件的方式:

btnStop.addEventListener('click', function() {
  removeAnimFrame();
  Velocity(ball, 'stop', true);
  this.disabled = true;
  btnPlay.disabled = false;
});

This code:

这段代码:

  • Removes the looping animation

    删除循环动画
  • Calls Velocity(ball, 'stop', true); to stop the animation

    调用Velocity(ball, 'stop', true); 停止动画

  • Disables the Play button

    禁用播放按钮

  • And restores the Stop button’s functionality.

    并恢复“ 停止”按钮的功能。

The interesting bit of code is the call to Velocity.js stop() method with an additional boolean (true or false) argument. This is necessary to clear the animation queue. If you leave this argument out and click the Stop button, the ball won’t immediately stop animating. It will stop animating only once all the queued Velocity calls have finished executing (see Clearing the Animation Queue, inside the Stop section in the Velocity.js docs).

代码中有趣的一点是调用Velocity.js stop()方法以及一个附加的布尔值(true或false)。 这是清除动画队列所必需的。 如果忽略该参数并单击“ 停止”按钮,则球将不会立即停止动画。 仅当所有排队的Velocity调用完成执行后,它才会停止动画处理(请参阅Velocity.js文档中Stop部分中的Clearing Animation Queue )。

Have a peek at the demo to review the entire code:

观看演示以查看整个代码:

滚动动画 (Scrolling Animation)

With Velocity.js you can quickly implement both vertical and horizontal scrolling animation. Scrolling can be in relation to the entire page or a containing element. Either way, you always call Velocity on the element you’re scrolling into view.

使用Velocity.js,您可以快速实现垂直和水平滚动动画。 滚动可以相对于整个页面或一个包含元素。 无论哪种方式,您总是在要滚动到view的元素上调用Velocity

The demo below uses two links: clicking the top link scrolls the container to the last section, clicking the bottom link scrolls the container to the first section.

下面的演示使用两个链接:单击顶部链接将容器滚动到最后一部分,单击底部链接将容器滚动到第一部分。

Since the scrolling action is the same for both links, to avoid repeating the same code twice, organize it into a function. Here’s what it looks like:

由于两个链接的滚动动作相同,因此为避免重复两次相同的代码,请将其组织为一个函数。 看起来是这样的:

const scrolling = (element, container, direction) => {
  let offsetDistance = 0;
  direction === 'up' ? offsetDistance = -200 : 200;
   //velocity call
   Velocity(element, 'scroll', {
    container: container,  
    duration: 500, 
    offset: offsetDistance, 
    easing: 'ease-out'
  }); 
};
  • The element parameter stands for the element that you want to scroll into view, in this case either the first or the last section, depending on the direction of the scroll

    element参数代表要滚动到视图中的元素,在这种情况下,第一部分或最后一部分,取决于滚动方向

  • The direction is stored in the direction parameter and its functionality is determined by how the ternary operator works. In particular: if the value of direction is ‘up’ (direction === 'up' ?), then the value of offsetDistance is -200px, which moves the page 200px above the element being scrolled into view (offsetDistance = -200), otherwise the value of offsetDistance will be 200px (: 200), which offsets the page 200px below the element being scrolled into view. The offsetDistance parameter will store a value for Velocity’s offset option property, which lets you offset the target scroll position by a specified amount in pixels

    方向存储在direction参数中,其功能由三元运算符的工作方式确定。 特别是:如果direction值为'up'( direction === 'up' ? ),则offsetDistance值为-200px,这会将页面移动到要滚动到视图中的元素上方200px( offsetDistance = -200 ) ,否则offsetDistance的值将为200px( : 200 ),这会将页面滚动到要滚动到视图中的元素下方200px处。 offsetDistance参数将存储Velocity的offset选项属性的值,该值使您可以将目标滚动位置偏移指定量(以像素为单位)

  • Because the scrolling in the demo is not relative to the browser window but to a containing element, the Velocity call needs that information, which in the code above is stored in the container parameter. Also because of this, set the CSS position property of the containing element to either relative, absolute, or fixed; static doesn’t work.

    因为演示中的滚动与浏览器窗口无关,而是与包含元素有关,所以Velocity调用需要该信息,该信息在上面的代码中存储在container参数中。 也正因为如此,将contains元素CSS position属性设置为relativeabsolutefixedstatic不起作用。

Finally, you handle the click event on the relevant links by calling the function above. For instance, to scroll to the last section, your event handler could look something like this:

最后,您可以通过调用上面的函数来处理相关链接上的click事件。 例如,要滚动到最后一部分,您的事件处理程序可能如下所示:

Link.addEventListener('click', (e) => {
  e.preventDefault();
  scrolling(lastSection, scrollerContainer, 'down');
});

Here’s the full code:

这是完整的代码:

See the Pen Page scrolling with Velocity.js by SitePoint (@SitePoint) on CodePen.

请参阅CodePen上的SitePoint ( @SitePoint ) 使用Velocity.js进行的笔页滚动

SVG动画 (SVG Animation)

Velocity can animate any property with a single number value, including CSS properties applied to SVGs and SVG-specific properties, e.g., fill, stroke, stroke-width, stroke-color, rx, ry, etc.

Velocity可以为具有单个数字值的任何属性设置动画,包括应用于SVGCSS属性和SVG特定的属性,例如fillstrokestroke-widthstroke-colorrxry等。

For a full list of SVG properties Velocity.js can animate, have a look at the Velocity docs on SVG animation.

有关SVG属性的完整列表,Velocity.js可以进行动画处理,请查看SVG动画上的Velocity文档

The demo below shows an SVG image of a smiling fish. Bubbles fade in and out of view and its eye blinks every few seconds. If you click the Play button, the fish moves to the left of its container, disappears, returns and turns around.

下面的演示显示了一条微笑鱼的SVG图像。 气泡淡入淡出,每隔几秒钟眨眼一次。 如果单击“ 播放”按钮,鱼将移至其容器的左侧,消失,返回并转身。

Bug alert: unfortunately, IE/Edge browsers have no support for CSS transforms and Velocity does not provide a compatibility fix for this bug. Therefore, the demo doesn’t work as expected in those browsers.

错误警报 :不幸的是,IE / Edge浏览器不支持CSS转换,并且Velocity不提供此错误的兼容性修补程序。 因此,该演示在这些浏览器中无法正常运行。

使您的SVG图像准备好动画 (Get Your SVG Image Ready for Animation)

Before writing any code, make sure your SVG image is ready to be animated using Velocity.js.

在编写任何代码之前,请确保准备好使用Velocity.js对SVG图像进行动画处理。

  • Add class or ID attributes to the parts of the SVG you plan on animating. This will make it easy for you to target those parts in JavaScript

    将类别或ID属性添加到您计划制作动画的SVG的各个部分。 这将使您轻松定位JavaScript中的这些部分
  • If you want to animate some elements as a whole, wrap thos elements inside <g></g> tags and slap a class attribute or ID attribute for easy manipulation in your JavaScript code

    如果要整体上对某些元素进行动画处理,请将thos元素包装在<g></g>标记内,并拍打class属性或ID属性,以便在JavaScript代码中轻松操作

  • Simplify and optimize your graphics.

    简化和优化您的图形。

Velocity.jsJavaScript代码 (The JavaScript Code with Velocity.js)

Once again, package most of your code into functions, for more flexibility and less repetition.

再次将大多数代码打包到函数中,以提高灵活性和减少重复。

As an example, here’s the function that moves the fish:

例如,这是移动鱼的函数:

const moveFish = (elem, moveBy, initialPos, btn, bool = false) => {
  Velocity(elem, {
  translateX: [moveBy, initialPos]
}, {
    duration: 5000,
    easing: 'linear',
    complete: () => {
      if(bool) {
        btn.disabled = false;
      }
    }
  });
};

The syntax for SVG animation is not different from animating HTML elements. Here’s what the code above does in more detail:

SVG动画的语法与动画HTML元素没有什么不同。 以下是上面代码的详细信息:

  • The code makes a Velocity call on an element and uses forcefeeding to set the value for the translateX property, which determines both final and initial positions for the element. When you later call this function the argument you will supply for the element parameter will be a reference to the SVG fish

    该代码对元素进行Velocity调用,并使用强制进给来设置translateX属性的值,该属性确定元素的最终位置和初始位置。 以后调用此函数时,将为element参数提供的参数将是对SVG鱼的引用

  • It takes advantage of Velocity.js built-in complete() method to activate the Play button only after the entire animation ends. This is to prevent users from repeatedly pressing the button during the course of the animation, which would build the animation queue

    仅在整个动画结束后,才利用Velocity.js内置的complete()方法激活“ 播放”按钮。 这是为了防止用户在动画过程中反复按下按钮,否则会建立动画队列

  • After the animation is finished and the Play button is active again, users can choose to replay the animation, if they so wish. This functionality works via the bool parameter. If the value of bool is true when the moveFish() function is called, the native Velocity.js complete() method inside moveFish() fires at the end of the animation and reactivates the button

    动画结束并再次激活“ 播放”按钮后,用户可以根据需要选择重播动画。 此功能通过bool参数起作用。 如果值bool为真时moveFish()函数被调用时,本地Velocity.js内完整()方法moveFish()在动画结束火灾和重新激活按钮

  • Finally, notice another ES6-specific feature, default parameters. You set a default value, in this case is bool = false, and when you call moveFish() you can choose to leave out the corresponding argument because what you set as your default will be automatically applied. Alternatively, you can change the default by explicitly entering an argument. To see this in action, pay attention to the next bit of code, which contains a call to the function above.

    最后,请注意另一个ES6特定功能,即默认参数 。 设置默认值,在这种情况下为bool = false ,并且在调用moveFish()时可以选择省略相应的参数,因为设置为默认值的设置将自动应用 。 或者,您可以通过显式输入参数来更改默认值。 要实际操作,请注意下一部分代码,其中包含对上述函数的调用。

To achieve different moving animations, call moveFish() a number of times using different arguments inside a master function, like this:

要实现不同的动画效果,请使用master函数内部的不同参数多次调用moveFish() ,如下所示:

const play = () => { 
  moveFish(fish, '-1000', 0, btnPlay);
  moveFish(fish, 0, '-1000', btnPlay, true);
  //more functions here
};

Take note of the different ways in which you call moveFish(): the first time without the fifth argument and the second time with the fifth argument with a value of true. In the first case, the value for the fifth argument is the default parameter you supplied when you wrote the moveFish() function.

请注意调用moveFish()的不同方式:第一次不带第五个参数,第二次不带第五个参数,其值为true 。 在第一种情况下,第五个参数的值是编写moveFish()函数时提供的默认参数。

Finally, just call the play() function on the Play button’s click event:

最后,只需在“ 播放”按钮的click事件上调用play()函数:

btnPlay.addEventListener('click', function() {
  this.disabled = true;
  play();
});

To see all the pieces of the animation at work, have fun experimenting with the demo below.

要查看动画的所有片段,请尝试以下演示,有趣。

See the Pen SVG Animation with Velocity.js by SitePoint (@SitePoint) on CodePen.

见笔SVG动画与Velocity.js由SitePoint( @SitePoint上) CodePen

速度UI包 (Velocity UI Pack)

You can complement Velocity.js with Velocity UI Pack, a plugin that greatly improves your animation workflow.

您可以用Velocity UI Pack补充Velocity.js,Velocity UI Pack可以大大改善动画工作流程。

You need to download the UI pack and reference it below the main Velocity.js library.

您需要下载UI包并在Velocity.js主库下面引用它。

This plugin gives access to cool pre-registered effects like bounceIn/Out, swirlIn/Out, fadeIn/Out, etc. You can see the list of all effects you can get out of the box in the UI Pack docs. On top of this, you can also register your own custom effects.

这个插件可以访问很酷的预先注册的效果,例如bounceIn / OutscrewIn / OutfadeIn / Out等。您可以在UI Pack文档中查看可以立即使用的所有效果的列表。 最重要的是,您还可以注册自己的自定义效果。

In the demo below, I use Velocity.js UI Pack to hide a form after submission and show a success icon to the user.

在下面的演示中,我使用Velocity.js UI Pack在提交后隐藏表单,并向用户显示成功图标。

Here’s what the Velocity call to hide the form looks like (inside the hideForm() function):

这是隐藏表单的Velocity调用的样子(在hideForm()函数内部):

Velocity(formEl,'transition.bounceUpOut', 500);
  • The first argument is the element you are animating, i.e., the form in this case

    第一个参数是您要设置动画元素 ,即本例中的形式

  • The second argument is one of the UI Pack’s pre-registered effects, i.e., bounceUpOut (the effects are divided into transitions and callouts and you prefix the effect with the appropriate category)

    第二个参数是UI Pack的预注册效果之一 ,即bounceUpOut (效果分为过渡标注,并为效果加上适当的类别作为前缀)

  • The last one is the duration of the animation.

    最后一个是动画的持续时间

Have a look at the demo below for all the details:

请查看下面的演示以获取所有详细信息:

更多资源 (More Resources)

These are some links to resources around the web, where you can learn more on Velocity.js:

这些是到网络上资源的一些链接,您可以在其中了解有关Velocity.js的更多信息:

结论 (Conclusion)

In this article I have introduced Velocity.js and showed how you can work with it without the jQuery dependency.

在本文中,我介绍了Velocity.js,并展示了如何在没有jQuery依赖的情况下使用它。

I have found the library’s syntax intuitive and user-friendly, even more so for those who are familiar with the jQuery library. Documentation is thorough and offers tons of demos to illustrate each feature.

我发现该库的语法直观且易于使用,对于那些熟悉jQuery库的人而言更是如此。 文档非常详尽,并提供大量演示来说明每个功能。

Below are just a few considerations, which relate to the use of Velocity.js without jQuery and to SVG animation:

以下是一些注意事项,与不使用jQuery的Velocity.js的使用以及SVG动画有关:

  1. The Velocity.js UI Pack exposes a function called $.Velocity.RunSequence(), which combines multiple Velocity calls into a a single effect you can then reference by name. This feature would have been super handy when dealing with more complex animation sequences. Unfortunately, I didn’t manage to make it work without jQuery

    Velocity.js UI Pack公开了一个名为$.Velocity.RunSequence()的函数,该函数将多个Velocity调用合并为一个效果,您可以按名称进行引用。 当处理更复杂的动画序列时,此功能将非常方便。 不幸的是,如果没有jQuery,我无法使其正常运行

  2. Such a powerful library would have benefited from making available a timeline. Using Tweene could have been a solution, but again, integration between Tweene and Velocity without jQuery is not straightforward

    这样一个功能强大的库将从提供时间表中受益。 使用Tweene本来可以是一个解决方案,但是同样地,在没有jQuery的情况下,Tweene和Velocity之间的集成并不简单
  3. Not offering a fix for IE/Edge browsers’ lack of support for CSS transforms is a limiting factor for me when using Velocity with SVG.

    在SVG上使用Velocity时,没有为IE / Edge浏览器提供对CSS转换的不支持的修复程序是我的一个限制因素。

It’s highly likely the points above will be addressed in the future by the developers behind the project. In the meantime, remember that Velocity.js is open-source. Consequently, if you can think of any enhancements or find a bug, you have the option of sending a pull request or leaving a comment in the issues section of the Velocity.js repo on GitHub.

该项目的开发人员将来很可能会解决以上问题。 同时,请记住Velocity.js是开源的。 因此,如果您可以考虑任何增强功能或发现错误,则可以选择发送请求请求或在GitHub上Velocity.js存储库的问题部分中留下评论。

Have you used Velocity.js for your animation projects? What has your experience been like? Do you have any animations you’d like to share? Use the comment box below to let us know.

您是否已将Velocity.js用于动画项目? 您的经历如何? 您想分享任何动画吗? 使用下面的评论框让我们知道。

Credits: for the SVG demo, the graphic is an adapted version of the Goldfish from Pixabay, the featured image is courtesy of Unsplash, and the woman photographer image in the last demo is courtesy of Gratisography

鸣谢:对于SVG演示,该图形是来自png金鱼的改编版,特色图像由Unsplash提供 ,最后一个演示中的女摄影师图像由Gratisography提供

翻译自: https://www.sitepoint.com/how-to-use-velocity-js-without-jquery/

velocity.js

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值