Event: “transitionend”
When the CSS animation finishes, the event triggers.
It is widely used to do an action after the animation is done. Also we can join animations.
For instance, the ship in the example below starts to sail there and back when clicked, each time farther and farther to the right:
The animation is initiated by the function that re-runs each time the transition finishes, and flips the direction:
The event object for has a few specific properties:
- The property that has finished animating. Can be good if we animate multiple properties simultaneously.
- The time (in seconds) that the animation took, without .
Значения свойства
Значение | Описание |
---|---|
transition-property | Указывает имя свойства CSS для которого используется переходный эффект. Значение по умолчанию all. |
transition-duration | Определяет, сколько секунд или миллисекунд эффект перехода занимает времени. Значение по умолчанию 0 секунд. |
transition-timing-function | Используется, чтобы описать, как рассчитываются промежуточные значения CSS свойства, которое находится под воздействием эффекта перехода, используя при этом математическую функцию (кубическую кривую Безье). Это, по сути, позволяет создать кривую «разгона», так что скорость перехода может меняться в течение длительности эффекта перехода. Значение по умолчанию ease. |
transition-delay | Указывает, когда эффект перехода начнется (выступает в роли задержки начала эффекта). Значение по умолчанию 0 секунд. |
initial | Устанавливает свойство в значение по умолчанию. |
inherit | Указывает, что значение наследуется от родительского элемента. |
Creating your own timing function with cubic-bezier
A Cubic-bezier is a set of four values that determine your transition-timing-function. It looks like this:
Don’t worry about the , , and . You’ll never create cubic-bezier curves by writing numbers yourself (unless you already know what they mean and you’re tweaking your timing function for perfection).
You can rely on both Chrome and Firefox’s trusty developer tools to help you create your curves. To use it, you add a into an element, then open up devtools and click on the timing function.
Both Chrome and Firefox provides you with a cubic-bezier tool
See the Pen
CSS Transition Timing Functions
by Zell Liew (@zellwk) onCodePen.
Going in-depth about creating your own bezier curves for your animations is out of scope for today’s article. If you’re interested, you can find more information about cubic-bezier curves in ”Understanding CSS Timing Functions” by Stephen Greig.
The Component
is a built-in component: this means it is available in any component’s template without having to register it. It can be used to apply enter and leave animations on elements or components passed to it via its default slot. The enter or leave can be triggered by one of the following:
- Conditional rendering via
- Conditional display via
- Dynamic components toggling via the special element
- Changing the special attribute
This is an example of the most basic usage:
template
css
Toggle Fade
hello
TIP
only supports a single element or component as its slot content. If the content is a component, the component must also have only one single root element.
When an element in a component is inserted or removed, this is what happens:
-
Vue will automatically sniff whether the target element has CSS transitions or animations applied. If it does, a number of will be added / removed at appropriate timings.
-
If there are listeners for , these hooks will be called at appropriate timings.
-
If no CSS transitions / animations are detected and no JavaScript hooks are provided, the DOM operations for insertion and/or removal will be executed on the browser’s next animation frame.
Пример использования
<!DOCTYPE html> <html> <head> <title>Пример использования универсального свойства transition в CSS</title> <style> div { width : 100px; /* устанавливаем ширину блока */ height : 60px; /* устанавливаем высоту блока */ background-color : khaki; /* устанавливаем цвет заднего фона */ color : khaki; /* устанавливаем цвет шрифта */ border : 2px solid orange; /* устанавливаем сплошную границу размером 2px оранжевого цвета */ } div:hover { width : 300px; /* устанавливаем ширину блока при наведении на элемент */ height : 250px; /* устанавливаем высоту блока при наведении на элемент */ background : CornflowerBlue; /* устанавливаем цвет заднего фона при наведении*/ } .test { transition : width 2s ease 100ms, height 1s linear 2s, background 0s 4s; /* Для свойства width мы устанавливаем длительность эффекта перехода равную 2 секунды, при этом эффект перехода начинается медленно, затем незначительно ускоряется и в конце опять замедляется (ease) и это всё происходит с предварительной задержкой в 100 миллисекунд. Для свойства height мы устанавливаем длительность эффекта перехода равную 1 секунде, при этом эффект перехода происходит с одинаковой скоростью от начала до конца (linear) и это всё происходит с предварительной задержкой в 2 секунды. Свойство background будет применено с задержкой 4 секунды. */ } </style> </head> <body> <div class = "test">Свойство transition в CSS</div> </body> </html>
Все свойства эффекта перехода (переход между двумя состояниями элемента) в одном объявлении (универсальное свойство transition).
Пример выдвигающегося поиска на CSS, используя селектор атрибута (с указанным значением) и универсальное свойство transition:
<!DOCTYPE html> <html> <head> <title>Выдвигающийся поиск на CSS</title> <style> input { width : 20%; /* устанавливаем ширину элемента input с указанным атрибутом и значением (type="text") */ transition : width 500ms ease-in-out; /* Для свойства width мы устанавливаем длительность эффекта перехода равную 500 ms, при этом эффект перехода начинается с медленного старта и заканчивается медленно (ease-in-out) */ } input:focus { width : 40%; /* устанавливаем ширину элемента input с указанным атрибутом и значением (type="text") при получении фокуса */ } </style> </head> <body> Поиск: <input type = "text" name = "poisk" placeholder = "введите запрос"> </body> </html>
Выдвигающийся поиск на css (универсальное свойство transition и селектор атрибутов).CSS свойства
transition-delay
In we can specify the delay before the animation. For instance, if is and is , then the animation starts 1 second after the property change and the total duration will be 2 seconds.
Negative values are also possible. Then the animation is shown immediately, but the starting point of the animation will be after given value (time). For example, if is and is , then animation starts from the halfway point and total duration will be 1 second.
Here the animation shifts numbers from to using CSS property:
Result
script.js
style.css
index.html
The property is animated like this:
In the example above JavaScript adds the class to the element – and the animation starts:
We could also start it from somewhere in the middle of the transition, from an exact number, e.g. corresponding to the current second, using a negative .
Here if you click the digit – it starts the animation from the current second:
Result
script.js
style.css
index.html
JavaScript does it with an extra line:
Understanding CSS3 Transitions
Normally when the value of a CSS property changes, the rendered result is instantly updated. A common example is changing the background color of a button on mouse hover. In a normal scenario the background color of the button is changes immediately from the old property value to the new property value when you place the cursor over the button.
CSS3 introduces a new transition feature that allows you to animate a property from the old value to the new value smoothly over time. The following example will show you how to animate the of an HTML button on mouse hover.
Example
Try this code
You must specify at least two properties and the (greater than 0), to make the transition occur. However, all the other are optional, as their default values don’t prevent an transition from happening.
To make the transition occur, you must specify at least two things — the name of the CSS property to which you want to apply the transition effect using the CSS property, and the duration of the transition effect (greater than 0) using the CSS property. However, all the other are optional, as their default values don’t prevent a transition from happening.
Note: Not all CSS properties are animatable. In general, any CSS property that accepts values that are numbers, lengths, percentages, or colors is animatable.
Summary
CSS animations allow smoothly (or step-by-step) animated changes of one or multiple CSS properties.
They are good for most animation tasks. We’re also able to use JavaScript for animations, the next chapter is devoted to that.
Limitations of CSS animations compared to JavaScript animations:
Merits
- Simple things done simply.
- Fast and lightweight for CPU.
Demerits
- JavaScript animations are flexible. They can implement any animation logic, like an “explosion” of an element.
- Not just property changes. We can create new elements in JavaScript as part of the animation.
In early examples in this chapter, we animate , , , , etc. In real life projects, we should use and for better performance.
The majority of animations can be implemented using CSS as described in this chapter. And the event allows JavaScript to be run after the animation, so it integrates fine with the code.
But in the next chapter we’ll do some JavaScript animations to cover more complex cases.
CSS Tutorial
CSS HOMECSS IntroductionCSS SyntaxCSS SelectorsCSS How ToCSS CommentsCSS Colors
Colors
RGB
HEX
HSL
CSS Backgrounds
Background Color
Background Image
Background Repeat
Background Attachment
Background Shorthand
CSS Borders
Borders
Border Width
Border Color
Border Sides
Border Shorthand
Rounded Borders
CSS Margins
Margins
Margin Collapse
CSS PaddingCSS Height/WidthCSS Box ModelCSS Outline
Outline
Outline Width
Outline Color
Outline Shorthand
Outline Offset
CSS Text
Text Color
Text Alignment
Text Decoration
Text Transformation
Text Spacing
Text Shadow
CSS Fonts
Font Family
Font Web Safe
Font Fallbacks
Font Style
Font Size
Font Google
Font Pairings
Font Shorthand
CSS IconsCSS LinksCSS ListsCSS Tables
Table Borders
Table Size
Table Alignment
Table Style
Table Responsive
CSS DisplayCSS Max-widthCSS PositionCSS Z-indexCSS OverflowCSS Float
Float
Clear
Float Examples
CSS Inline-blockCSS AlignCSS CombinatorsCSS Pseudo-classCSS Pseudo-elementCSS OpacityCSS Navigation Bar
Navbar
Vertical Navbar
Horizontal Navbar
CSS DropdownsCSS Image GalleryCSS Image SpritesCSS Attr SelectorsCSS FormsCSS CountersCSS Website LayoutCSS UnitsCSS SpecificityCSS !importantCSS Math Functions
#Spring
An animation that simulates spring physics for realistic motion.
This is the default animation for physical values like , , and .
type: «spring»
Set to to animate using spring physics for natural movement. Type is set to by default.
Copy<motion.div
animate={{ rotate: 180 }}
transition={{ type: ‘spring’ }}
/>
duration: number
The duration of the animation, defined in seconds. Spring animations can be a maximum of 10 seconds.
If is set, this defaults to .
Note: and will be overridden if , or are set.
Copy<motion.div
animate={{ x: 100 }}
transition={{ type: «spring», duration: 0.8 }}
/>
bounce: number
determines the «bounciness» of a spring animation.
is no bounce, and is extremely bouncy.
If is set, this defaults to .
Note: and will be overridden if , or are set.
Copy<motion.div
animate={{ x: 100 }}
transition={{ type: «spring», bounce: 0.25 }}
/>
damping: number
Strength of opposing force. If set to 0, spring will oscillate indefinitely. Set to by default.
Copy<motion.a
animate={{ rotate: 180 }}
transition={{ type: ‘spring’, damping: 300 }}
/>
mass: number
Mass of the moving object. Higher values will result in more lethargic movement. Set to by default.
Copy<motion.feTurbulence
animate={{ baseFrequency: 0.5 } as any}
transition={{ type: «spring», mass: 0.5 }}
/>
stiffness: number
Stiffness of the spring. Higher values will create more sudden movement. Set to by default.
Copy<motion.section
animate={{ rotate: 180 }}
transition={{ type: ‘spring’, stiffness: 50 }}
/>
velocity: number
The initial velocity of the spring. By default this is the current velocity of the component.
Copy<motion.div
animate={{ rotate: 180 }}
transition={{ type: ‘spring’, velocity: 2 }}
/>
restSpeed: number
End animation if absolute speed (in units per second) drops below this value and delta is smaller than . Set to by default.
Copy<motion.div
animate={{ rotate: 180 }}
transition={{ type: ‘spring’, restSpeed: 0.5 }}
/>
restDelta: number
End animation if distance is below this value and speed is below . When animation ends, spring gets “snapped” to. Set to by default.
Copy<motion.div
animate={{ rotate: 180 }}
transition={{ type: ‘spring’, restDelta: 0.5 }}
/>
Подготовка
Все далее описанные анимационные эффекты выполнены на блоке DIV. Итак, для начала опишем базовые свойства для блока:
12345678 |
.experiment{ width400px; height200px; background#676470; /* главное свойство */ transitionall 0.3s ease;} |
Значение свойства Transition состоит и 3 составляющих: transition-property — all, transition-duration — 0.3s и третьей величины, transition-timing-function — ease, также есть еще одна составляющая (transition-delay далее в таблице).
Наименование | Описание | Значение |
---|---|---|
transition-property | Свойство, к которому применяем анимацию | Практически любое свойство CSS: color, background, width, font-size и т.д. all — все свойства. |
transition-duration | Длительность анимации | Время в секундах: 0.5s — полсекунды, 60s — одна минута и т.д. |
transition-timing-function | Временная функция, используемая для анимации | ease, linear, ease-in-out, ease-in, ease-out, cubic-bezier |
transition-delay | Задержка анимации | Время в секундах: 0.5s — полсекунды, 60s — одна минута и т.д. |
Теперь переходим к эффектам.
Working with Multiple Transitions…and So On
The last thing we are going to talk about is something that I briefly
mentioned earlier around having multiple transitions, listening to
multiple transition properties, and so on. Let’s quickly look at some of
the common cases in this section.
Multiple Transitions
Declaring multiple transitions is pretty straightforward. When using
the transition shorthand, separate each
transition’s property values with a comma:
transition: width .5s ease-in, border-radius 1s linear;
For the longhand form, simply tackle on any additional values as
needed to the appropriate transition property:
transition-property: width, border-radius; transition-duration: .5s, 1s; transition-timing-function: ease-in, linear;
If you have a mismatched number of values, the standard behavior for
ensuring your CSS properties have well-defined values kicks in.
Listening to Multiple Properties
If you want to listen to a handful of properties individually, just
use the longhand version and list all of the properties you want your
transition to listen to in the
transition-property property:
transition-property: width, border-radius, background-color; transition-duration: .5s; transition-timing-function: ease-out;
What you’ve basically defined is three separate transitions (one for
each transition-property value) that each have a duration of .5 seconds
with an ease-out timing function specified. This is all
should be pretty straightforward.
Wrapping up
CSS Transitions are the easiest way to perform animations. You can create transitions either with the shorthand or with properties.
To create a transition, you overwrite a property in a class (or psuedo class), and you specify the property to transit in or .
Remember to change your so your animation looks more real!
If you loved this article, you’ll love learn Learn JavaScript—a course that helps you learn to build real components from scratch with Javascript. Click here to find out more about Learn JavaScript if you’re interested.
How to make interactive components
Dealing with Imposter Syndrome