简体   繁体   中英

how can i change background-color of the body to a linear gradient color

i have wrote a code that changes background-color of the body element to a random linear-gradient combination of three colors, it's working but i think it's not a professional way to do this, since it's append a style element to the html hierarchy every time button is pressed..

the code of JS is :

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);
}

您可以简单地获取文档的 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}%)`;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM