很久没有写博客了,今天学习看到一个博客网站,停留了一会,被这个效果吸引住了,于是就把这块的代码搬过来了。
效果如下:很简单,就是停留一个页面,然后会随机变换背景颜色,下面是效果的GIF图片。
实现代码
- 首先这个背景是全都由 js 生成的,我们只需要创建一个 div 元素,然后将它设定为 fixed ,层级设定的低一点,在添加到 body 底下
- 然后这个背景色和随机数分别是一个随机生成颜色和随机数函数生成的
- 这些东西整合起来,就能实现一个随机生成的背景色,接下去就是背景隔一段时间自己改变,这就要通过定时器来完成
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>渐变背景</title>
</head>
<body>
</body>
</html>
<script>
let randomTimer
function randomColor() {
const r = randomInt(255)
const g = randomInt(255)
const b = randomInt(255)
const c = `#${r.toString(16)}${g.toString(16)}${b.toString(16)}000`
return c.slice(0, 7)
}
function randomInt(max) {
return Math.floor(Math.random() * max)
}
function randomBgImg() {
clearInterval(randomTimer)
const el = document.createElement('div')
const deg = randomInt(360)
el.id = 'random-light-bg'
el.style.cssText = `
position:fixed;
top:0;
left:0;
right:0;
bottom:0;
z-index:-99;
transition: 1s linear;`
el.style.backgroundImage =
`linear-gradient(${deg}deg, ${randomColor()} 0%, ${randomColor()} 100%)`
document.body.appendChild(el)
function setBg() {
const randomBg =
`linear-gradient(${deg}deg, ${randomColor()} 0%, ${randomColor()} 100%)`
el.style.opacity = '.3'
setTimeout(() => {
el.style.backgroundImage = randomBg
el.style.opacity = '1'
}, 1000)
}
randomTimer = setInterval(setBg, 10000)
}
randomBgImg();
</script>