Css stop infinite animation

Css Animation

Можно управлять длительностью анимации, повторением, направлением, типом движения и шагами. Анимировать можно любые элементы, в том числе псевдо-элементы.

Обязательное условие — наличие конкретных значений. Свойства со значением auto не анимируются.

Сафари в настоящее время не поддерживает анимацию псевдоэлементов, для просмотра записи воспользуйтесь другими браузерами

@keyframes move  40%  left: 50%; bottom: 75%; animation-timing-function: ease-in; > 80%  left: 90%; bottom: -10em; > >
.sun  animation: move 15s infinite linear; >

infinite — бесконечное повторение

@keyframes

Сама анимация задается внутри блока @keyframes . После @keyframes задается имя анимации, а потом внутри фигурных скобок — её шаги.

Шаги можно задавать через проценты или с помощью ключевых слов from и to . При этом в шагах можно менять тип анимации ( animation-timing-function ):

Animation-name

Возможные значения: одно или несколько имен анимации. Значение по умолчанию: нет.

animation-name: move; — одна анимация.

animation-name: move, sun-color; — две анимации, имена задаются через запятую.

Animation-duration

Возможные значения: время в секундах (s) или миллисекундах (ms). В случае нескольких анимаций время для каждой из них можно задать через запятую. Исходное значение — 0s.

Animation-timing-function

Плавная анимация

ease — скольжение (значение по умолчанию)

ease-in — ускорение к концу

ease-out — ускорение в начале

ease-in-out — более плавное скольжение, чем ease

cubic-bezier(число,число,число,число) позволяет задавать сложный тип анимации. Значения удобно подбирать на cubic-bezier.com.

Пошаговая анимация

step-start и step-end — позволяют задать пошаговую анимацию, обязательно задавать конкретные шаги. При этом с

step-start изменения происходят в начале шага, а с

step-end . Если выставить step-start , счетчик будет начинаться с единиц.

steps(число) — позволяет задать количество шагов, за которые будет выполнена анимация, при этом можно задать только последний шаг без необходимости указывать промежуточные.

Animation-iteration-count

число — сколько раз проиграть анимацию. infinite — бесконечное повторение.

Animation-direction

normal — анимация проигрывается в обычном направлении, с начала и до конца.

reverse — анимация проигрывается в обратном направлении, то есть с конца.

alternate — анимация проигрывается с начала и до конца, а затем в обратном направлении.

alternate-reverse — анимация проигрывается с конца до начала, а затем в обратном направлении.

Animation-play-state

running — анимация проигрывается (значение по умолчанию).

paused — анимация застывает на первом шаге.

Управлять шагом, где будет остановка, не получается, но можно останавливать анимацию по :hover :

Animation-delay

Возможные значения: время в секундах (s) или миллисекундах (ms). Значения могут быть отрицательными. В случае нескольких анимаций время для каждой из них можно задать через запятую. Исходное значение — 0s.

Animation-fill-mode

Свойство определяет будет ли анимация воздействовать на элемент вне времени воспроизведения анимации.

none — анимация воздействует на элемент только во время воспроизведения, по окончании элемент возвращается в исходное состояние.

forwards — анимация воздействует на элемент по окончании воспроизведения.

backwards — анимация воздействует на элемент до начала воспроизведения.

both — анимация воздействует на элемент и до начала, и после окончания воспроизведения.

Чтобы увидеть как backwards и both работают до начала воспроизведения анимации, задана задержка animation-delay: 3s; . Так же для этого имеет смысл открыть пример в новом окне.

Все эти свойства можно записать с помощью короткой записи, например:

animation: timing 5s infinite alternate;

Обязательные значения — имя анимации и длительность. Первое временное значение считается длительностью воспроизведения, второе — задержкой.

Сайдбар

Статьи

  • Математические функции в CSS
  • Адаптивное видео с помощью встроенных математических функций CSS
  • Недоступность в картинках
  • Единицы размеров в CSS
  • Генератор цветовых тем
  • Jekyll → Gatsby
  • Вариативные шрифты
  • Размеры в SVG
  • Адаптивный Pixel Perfect
  • Логотип не отвечает или временно недоступен
  • SVG-паттерны
  • Мыльные пузыри на SVG
  • SVG-градиенты
  • Весёлая консолька
  • SVG-маски
  • Умная прокрутка со Scroll Snap Points
  • CSS-анимации для ротации изображений
  • Анимированные SVG-маски
  • Странности обводки в SVG
  • SVG-прелоадеры
  • Анимируем градиенты ещё раз
  • Background-blend-mode
  • Возможности оформления SVG
  • CSS и SVG маски
  • Nth-child и nth-of-type
  • SVG-иконки
  • SVG: заливка и обводка
  • SVG-path
  • SVG: группировка и переиспользование элементов
  • SVG-фигуры и трансформации
  • SVG
  • СSS-градиенты и 3D
  • Рисовалка анимированных теней
  • Свежие CSS-паттерны
  • CSS-паттерны
  • Радиальные градиенты
  • Линейные градиенты
  • Крестики-нолики на CSS
  • Border-image
  • Электронные часы на CSS и JS.
  • Сколько весят селекторы?
  • Символы юникода
  • Свойство content
  • Анимируем CSS-градиенты
  • Текстовые эффекты
  • Древовидный список на CSS
  • Css-селекторы, часть 2
  • Css-селекторы
  • Контекст наложения
  • Два способа «прошить» элемент по краю
  • Box-sizing
  • Цвета в CSS
  • Фон под строчками: добавляем поля
  • Box-shadow
  • Css-фигуры: лепесток
  • Transform
  • Css Animation
  • 3D-куб
  • Border-radius
  • First letter
  • Эти глаза напротив
  • CSS-фигуры
  • Стрелки с помощью свойства border
  • Flexbox

Страницы

Проекты

Источник

CSS Animations, start and stop infinite animation on click

This is my code so far: HTML: Javascript: CSS: Solution: should be Question: I have two buttons that control the image above, and they basically change the image in the forward direction or reverse direction. It’s all achieved by chaining the animations on the #Link.

CSS Animations, start and stop infinite animation on click

Is there any way to do that without javascript or do I have to use JS to append/remove class from an object? Could you guys show me some live example? Right now I have something that works only on hover of the object:

 .clicker:hover + .circle < -webkit-animation: rotor 1.5s linear 0s infinite normal; -mox-animation: rotor 1.5s linear 0s infinite normal; -o-animation: rotor 1.5s linear 0s infinite normal; animation: rotor 1.5s linear 0s infinite normal; >.paused

Assuming this (from your CSS).

WITH PURE JAVASCRIPT:

WITH JQUERY:

You haven’t post your html, so the JavaScript/jQuery selectors I’m using are base on your CSS. For a more specific answer with the best selectors, you should show your html.

I’ve just realized that with this solution you could have a problem with your CSS, because .circle styles prevails over .paused , so the class is been toggled but the styles aren’t changing. You can easily solve it adjusting your CSS.

This is not possible in CSS, however if you are interested in a JavaScript example:

$(element).on('click', function () < if ($(target).hasClass('paused')) < $(target).removeClass('paused'); >else < $(target).addClass('paused'); >>); 

Replace element with the button or anchor that activates the class removal / addition. And replace target with the element that should animate.

This solution requires jQuery .

var active = document.querySelector('.active'); var div = document.querySelector('.wrap'); var hasAnimationPaused = false; var aniamtionPausedClass = 'paused'div.className += ' circle'; active.addEventListener('click', function(e) < var classNames = div.className.split(' '); if (!hasAnimationPaused) < div.className += ' ' + aniamtionPausedClass; hasAnimationPaused = true; >else < classNames.splice(classNames.indexOf(aniamtionPausedClass), 1); div.className = classNames.join(' '); hasAnimationPaused = false; >>)
.wrap < color: black; >@keyframes rotor < from < color: red; >50% < color: yellow; >to < color: blue; >> .circle < -webkit-animation: rotor 1.5s linear 0s infinite normal; -mox-animation: rotor 1.5s linear 0s infinite normal; -o-animation: rotor 1.5s linear 0s infinite normal; animation: rotor 1.5s linear 0s infinite normal; >.paused

Prevent multiple clicks until animation is done (jQuery), By adding a boolean flag whose status you can check before deciding what to do: // Are we in the middle of an animation? var

JQuery — Disable Click until all chained animations are complete

Question

The solution below is intended to slide down the groupDiv displaying div1 and enough space for div2 to slide in. It’s all achieved by chaining the animations on the #Link.Click() element.

It seems to bug out , though, when the link is clicked rapidly . Is there a way to prevent this? By perhaps disabling the Click function until the chained animations are complete? I currently have checks in place, but they don’t seem to be doing the job 🙁

Custom animate functions.

//Slide up or down and fade in or out jQuery.fn.fadeThenSlideToggle = function(speed, easing, callback) < if (this.is(":hidden")) < visibilityCheck("show", counter--); return this.slideDown().animate(,700, "easeInOutCirc", callback); > else < visibilityCheck("hide", counter++); return this.fadeTo(450, 0, "easeInOutCirc").slideUp(); > >; //Slide off page, or into overflow so it appears hidden. jQuery.fn.slideLeftToggle = function(speed, easing, callback) < if (this.css('marginLeft') == "-595px") < return this.animate(, speed, easing, callback); > else < return this.animate(, speed, easing, callback); > >; 

In the dom ready, i have this:

$('#Link').toggle( function() < if (!$("#div2 .tab").is(':animated')) < $("#GroupDiv").fadeThenSlideToggle(700, "easeInOutCirc", function() <$('#div2 .tab').slideLeftToggle();>); > >, function() < if (!$("#groupDiv").is(':animated')) < $('#div2 .tab').slideLeftToggle(function() <$("#groupDiv").fadeThenSlideToggle(700, "easeInOutCirc", callback);>); > > ); 

HTML structure is this:

The issue is your first animating the div#GroupDiv so your initial check if (!$(«#div2 .tab»).is(‘:animated’)) will be false until the groupDiv has finished animated and the callback is fired.

if (!$("#div2 .tab").is(':animated') && !$("#GroupDiv").is(':animated')) 

however I doubt this will cover really quick clicking. The safest is to unbind the event using

as the first line inside the if and you can then do away with the animated check. The downside to this is you will have to rebind using the callback you are passing through to your custom animation functions.

You can easily disable your links while animation is running

You can of course replace the $(‘a’) selector to match only some of the links.

Animating something that can be clicked repeatedly is something to look out for because it is prone for errors. I take it that you Problem is that animations queue up and are executed even when you have stopped clicking. The way I solved it was to use the stop() function on an Element.

Syntax: jQuery(selector).stop(clearQueue,gotoEnd) //both parameters are boolean
More Info

When I click on a button, I first stop the animation and clear the Queue, then i proceed to define the new animation on it. gotoEnd can stay false (default value) but you can try tochange it to true if you want, you might like the result.

Usage Example: jQuery(‘button#clickMe’).stop(true).animate().

you can put this first thing inside the click event

Learn the working of jQuery stop-animation, The jQuery stop() function accepts two parameters. Suppose we have a div element that has some text content with some animations. Now we need to stop all the

Playing/Stopping an animation with a button

I’ve got a basic animation going, but I want to be able to start and stop it at will — preferably with a simple function and none/limited jquery.

So far I’ve simply been switching the play state from «paused» to «running», but this hasn’t worked — ideas?

var AnimationStart; var AnimationStart = function()
  #Arena < color:#FFF; width:400px; height:300px; animation-iteration-count:infinite; animation-play-state:paused; animation:colorchange 20s; -moz-iteration-count:infinite; -ms-iteration-count:infinite; -o-iteration-count:infinite; -webkit-iteration-count:infinite; -moz-play-state:paused; -ms-play-state:paused; -o-play-state:paused; -webkit-animation-play-state:paused; -moz-animation:colorchange 20s; -ms-animation:colorchange 20s; -o-animation:colorchange 20s; -webkit-animation:colorchange 20s; >@keyframes colorchange < 0%5% 10% 15% 20% 25% 30% 35% 40% 45% 50% 55% 60% 65% 70% 75% 80% 85% 90% 95% 100% > @-moz-keyframes colorchange < 0%25% 50% 75% 100% > @-webkit-keyframes colorchange < 0%5% 10% 15% 20% 25% 30% 35% 40% 45% 50% 55% 60% 65% 70% 75% 80% 85% 90% 95% 100% > @-ms-keyframes colorchange < 0%50% 100% > @-o-keyframes colorchange < 0%50% 100% > 

onClick=»onclick = AnimationStart» should be onClick=»AnimationStart()»

How to stop jquery animate at onclick?, The .stop() function can be chained at the beginning of your call as well at the end to stop any animations. i.e. $(«#element»).stop().bounce

Stop animation after button click

I have two buttons that control the image above, and they basically change the image in the forward direction or reverse direction. My code is as follows:

 slider.fadeOut(400, function() < $(this).attr('src', images[index]); >).fadeIn(400); console.log(index); >); 

The problem is that if I have multiple button clicks, the image changes, but my fade animation happens like many times after, not just once to change the image.

Is there a way to stop the current animation, and proceed to fade in the next image? I just dont want multiply button clicks and then like 5 fade in’s after.

You can use the stop() method to achieve this. Providing true as the first parameter will also clear the queue of any following animations, which is useful if someone has repeatedly triggered the parent event. Try this:

slider.stop(true).fadeOut(400, function() < $(this).attr('src', images[index]); >).fadeIn(400); 

JQuery stop Animations, The jQuery stop() method is used to stop animations or effects before it is finished. Start sliding. Stop sliding. Click to slide down/up the panel.

Источник

Читайте также:  Список
Оцените статью