我编写了一个代码,将body元素的背景颜色更改为三种颜色的随机线性渐变组合,它可以工作,但是我认为这不是专业的方法,因为它将样式元素添加到了每次按下按钮都将显示html层次结构。
JS的代码是:
const foo = new Array(255);
const sheet = document.styleSheets;
const hText = document.getElementsByClassName('.heading__el');
const btn = document.getElementById('btn');
const color = document.querySelector('.color');
btn.addEventListener("click", function(){
let tiltDeg = 0;
let turningAngle1 = 0;
let turningAngle2 = 35;
let turningAngle3 = 100;
let opacity = 1;
let sheet = document.createElement('style');
sheet.innerHTML = `body { background: linear-gradient(${tiltDeg}deg, rgba(${getRandomNumber()}, ${getRandomNumber()}, ${getRandomNumber()}, ${opacity}) ${turningAngle1}%,
rgba(${getRandomNumber()}, ${getRandomNumber()}, ${getRandomNumber()}, ${opacity}) ${turningAngle2}%, rgba(${getRandomNumber()}, ${getRandomNumber()}, ${getRandomNumber()}, ${opacity}) ${turningAngle3}%) !important}`;
document.body.appendChild(sheet);
color.textContent = (`(${tiltDeg}deg, rgba(${getRandomNumber()}, ${getRandomNumber()}, ${getRandomNumber()}, ${opacity}) ${turningAngle1}%,
rgba(${getRandomNumber()}, ${getRandomNumber()}, ${getRandomNumber()}, ${opacity}) ${turningAngle2}%, rgba(${getRandomNumber()}, ${getRandomNumber()}, ${getRandomNumber()}, ${opacity}) ${turningAngle3}%)`)
color.style.fontSize = "0.5em";
});```
function getRandomNumber() {
return Math.floor(Math.random() * foo.length);
}
答案 0 :(得分:0)
您可以简单地获取文档的body元素,然后像这样更改其样式:
document.body.style.background = `linear-gradient(${tiltDeg}deg, rgba(${getRandomNumber()}, ${getRandomNumber()}, ${getRandomNumber()}, ${opacity}) ${turningAngle1}%, rgba(${getRandomNumber()}, ${getRandomNumber()}, ${getRandomNumber()}, ${opacity}) ${turningAngle2}%, rgba(${getRandomNumber()}, ${getRandomNumber()}, ${getRandomNumber()}, ${opacity}) ${turningAngle3}%)`;