Is it possible to define @keyfames percentage based on css variable?

  Kiến thức lập trình

I’ve got an animation that depends on the number of characters

It works fine with 20 characters:

const text = '20 characters length'

const speed = 0.1

const $container = document.querySelector('.wave')

$container.style.setProperty('--duration', `${speed * text.length}s`)

for (const [index, char] of Object.entries([...text])) {
  const $el = document.createElement('span')
  $el.innerHTML = char === ' ' ? ' ' : char
  $el.style.setProperty('--delay', `${index * speed}s`)
  $container.appendChild($el)
}
div>* {
  animation: anim var(--duration) step-start var(--delay) infinite;
  display: inline-block;
}

@keyframes anim {
  0%, 100% {
    translate: 0;
  }
  5% {
    translate: 0 -5px;
  }
}
<div class="wave"></div>

but only because 5% is the same as 1/20

If I change text length it’s going too fast

const text = '10 char...'

const speed = 0.1

const $container = document.querySelector('.wave')

$container.style.setProperty('--duration', `${speed * text.length}s`)

for (const [index, char] of Object.entries([...text])) {
  const $el = document.createElement('span')
  $el.innerHTML = char === ' ' ? ' ' : char
  $el.style.setProperty('--delay', `${index * speed}s`)
  $container.appendChild($el)
}
div>* {
  animation: anim var(--duration) step-start var(--delay) infinite;
  display: inline-block;
}

@keyframes anim {
  0%, 100% {
    translate: 0;
  }
  5% {
    translate: 0 -5px;
  }
}
<div class="wave"></div>

I would need to change 5% to 10% in @keyframes

const text = '10 char...'

const speed = 0.1

const $container = document.querySelector('.wave')

$container.style.setProperty('--duration', `${speed * text.length}s`)

for (const [index, char] of Object.entries([...text])) {
  const $el = document.createElement('span')
  $el.innerHTML = char === ' ' ? ' ' : char
  $el.style.setProperty('--delay', `${index * speed}s`)
  $container.appendChild($el)
}
div>* {
  animation: anim var(--duration) step-start var(--delay) infinite;
  display: inline-block;
}

@keyframes anim {
  0%, 100% {
    translate: 0;
  }
  10% {
    translate: 0 -5px;
  }
}
<div class="wave"></div>

I can change duration and delay using css variables.

Can I do the same with @keyframes list?

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT