我有一個改變頁面背景顏色的回圈,但是過渡太粗糙了。我想知道是否有辦法應用效果來平滑它們。使用 CSS 時的“輕松”之類的東西。
let x = document.body;
let color = ["blue", "green", "yellow", "red"];
setInterval(function() {
for(let y = 0; y < 4; y ){
x.style.backgroundColor = color[Math.floor(Math.random() * 3)];
}
}, 1000);
body {
background-color: black;
}
uj5u.com熱心網友回復:
使用 csstransition屬性
CSS
let x = document.body;
let color = ["blue", "green", "yellow", "red"];
setInterval(function() {
for(let y = 0; y < 4; y ){
x.style.backgroundColor = color[Math.floor(Math.random() * 3)];
}
}, 1000);
body {
background-color: black;
transition: background-color 2s;
}
JS
let x = document.body;
let color = ["blue", "green", "yellow", "red"];
setInterval(function() {
for(let y = 0; y < 4; y ){
x.style.backgroundColor = color[Math.floor(Math.random() * 3)];
x.style.transition = 'background-color 2s';
}
}, 1000);
body {
background-color: black;
}
uj5u.com熱心網友回復:
CSS 轉換(如 Pablo 的回答)可能是最簡單的解決方案。
但是,在過渡期間顏色會呈現灰色調。這是 RGB 顏色插值的副作用。詳細解釋顏色插值的相關博客文章:here。
另一種解決方案是在 javascript 中使用不同的顏色插值演算法。
d3-interpolatejavascript庫提供了多種顏色插值演算法。
下面的代碼片段展示了如何使用d3.interpolateLab函式平滑過渡顏色。
let x = d3.select('body');
let color = ["blue", "green", "yellow", "red"];
setInterval(function() {
for(let y = 0; y < 4; y ){
let currentColor = x.style('background-color')
x.transition()
.duration(800)
.styleTween('background-color'
, function() {
return d3.interpolateLab(
currentColor
, color[Math.floor(Math.random() * 3)]
)
})
}
}, 1000);
body {
background-color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/439915.html
標籤:javascript 循环
上一篇:使用prcomp對R中的面板資料進行主成分分析(PCA)
下一篇:如何創建這種回圈?
