【问题标题】:How to use a CSS transition in JavaScript?如何在 JavaScript 中使用 CSS 过渡?
【发布时间】:2021-12-15 21:37:41
【问题描述】:

我正在使用 JavaScript 更改网页上的颜色。它从数组中随机选择颜色以创建渐变,并每隔几秒更改这些颜色。

现在背景突然改变了。我希望背景颜色随着过渡而改变。 我试过BodyColor.style.transition ~ ,但没用。

const colors = [
  "#ff5e57",
  "#d2dae2",
  "#485460",
  "#ffa801",
  "#ffd32a",
  "#ff3f34"
];

const BodyColor = document.querySelector("body");

function randomNum(array) {
  if (!array) {
    var array = [];
  }
  let n = Math.floor(Math.random() * 18);
  if (array.length < 2 && array.indexOf(n) < 0) {
    array.push(n);
    return randomNum(array);
  } else {
    return array;
  }
}

function changeBackground() {
  BodyColor.style.background = `linear-gradient(to right, ${colors[randomNum()[0]]},${colors[randomNum()[1]]})`;
}

changeBackground();
setInterval(changeBackground, 2000);

【问题讨论】:

  • 你能解释一下“不工作”是什么意思吗?另外,您确定正在调用changeBackground() 吗?我会在你的changeBackground() 中添加一个alert("hello world!");,看看它是否会在页面刷新时弹出或触发函数调用。
  • 一个现已删除的答案指向这篇关于 transitioning gradients 的博文。您能否澄清您的问题是否是您想要渐变的平滑过渡?因为现在你的问题说它不起作用,但背景正在发生变化,它只是突然发生了。
  • 我想在changeBackground() 中添加过渡,但我不知道该怎么做......

标签: javascript css css-transitions linear-gradients


【解决方案1】:

正如 Alexis88 指出的那样,您不能直接使用过渡,他指出的链接使用不透明度更改来放置该过渡。

我通过添加一个类来替换 css ::hover 来调整此解决方案。

为了改变颜色的值,我使用了 css 变量

过渡分两个阶段进行
1- 随机选择构成新渐变的 2 种颜色,然后添加 css 类
2-一旦过渡完成,但代替这2种默认颜色并删除类

稍微复杂的一面是随机选择 2 种颜色,这里可能的组合数量是 6 x 5,为 2 种颜色。是的,这不是一个镐系统。我通过拒绝 3 个时期的历史中的任何组合来推动这个选择,并且还强加了 2 种颜色的系统变化

一些有用的链接:
-IIFE -Arrow function expressions -Using CSS variables -transitionend event

const BgChange =(_=>  // IIFE code
  {
  const
    classTransit = 'newBG'
  , colors       = [ '#ff5e57', '#d2dae2', '#485460', '#ffa801', '#ffd32a', '#ff3f34' ]
  , subSet       = colors.length -1
  , combinations = colors.length * subSet
  , choices = 
    { prevs : [-1,-1,-1]  // previous BG choices 
    , i_p   : 0           // index on
    , i_pMx : 3           // choices.prevs.length
    , last  : { c1: -1, c2: -1 }
    , curr  : { c1:  0, c2:  0 }
    }
  , newColors =_=>
    {
    let x;
    do {
      x  = Math.floor(Math.random() *combinations)
      choices.curr.c1 = Math.floor(x / subSet)
      choices.curr.c2 = x % subSet
      if (choices.curr.c2 >= choices.curr.c1) choices.curr.c2++
    } while
      ( choices.prevs.includes(x)
      || choices.last.c1 === choices.curr.c1
      || choices.last.c2 === choices.curr.c2
      )
    choices.prevs[choices.i_p++] = x
    choices.i_p %= choices.i_pMx
    }
    ;
  // -----   init first BG
  newColors()
  for ( let color in choices.curr ) 
    document.body.style.setProperty(`--${color}`, colors[choices.curr[color]]);
  Object.assign( choices.last, choices.curr )

  document.body.addEventListener('transitionend', _=>
    {
    if (document.body.classList.contains(classTransit))
      {
      for ( let color in choices.curr ) 
        document.body.style.setProperty(`--${color}`, colors[choices.curr[color]]);
      document.body.classList.remove(classTransit)
      }
    });

  return _=>  // transition BG function
    {
    newColors()
    for ( let color in choices.curr ) 
        document.body.style.setProperty(`--${color}a`, colors[choices.curr[color]]);
    document.body.classList.add(classTransit)
    }
  })()

// here we are!
setInterval( BgChange, 4000)
body {
  --c1   : #ffffff;
  --c1a  : #ffffff;
  --c2   : #ffffff;
  --c2a  : #ffffff;
  margin           : 0;
  width            : 100vw;
  height           : 100vh;
  position         : relative;
  background-image : linear-gradient( to right, var(--c1), var(--c2) );
  z-index          : 1;
  }
body::before {
  position         : absolute;
  content          : '';
  top              : 0;
  right            : 0;
  bottom           : 0;
  left             : 0;
  background-image : linear-gradient( to right, var(--c1a), var(--c2a) );
  z-index          : -1;
  transition       : opacity 0.5s linear;
  opacity          : 0;
  }
body.newBG::before {
  opacity          : 1;
  }

【讨论】:

  • @Alexis88 谢谢 :)
猜你喜欢
  • 1970-01-01
  • 2012-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-27
  • 1970-01-01
  • 2012-08-21
相关资源
最近更新 更多