Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

javascript - How to change the color of multiple objects with one button?

I want to change the color of multiple objects (footer, divs, text) background and text color, with one button. I tried using button javascript, but I don't want name multiple objects button in order to change their color. Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this First create a button HTML whit the id "btnChangeColor"

<button id="btnChangeColor" class="btn btn-primary">Change Color</button>

With JavaScript add the listener and with the DOM get all elements to change.

const btnChangeColor =    document.querySelector('#btnChangeColor');
const footer =            document.querySelector('footer');
const divs =              document.querySelectorAll('div');

btnChangeColor.addEventListener('click', () => {
    footer.classList.add('custom-theme');
    divs.forEach(item => {
        item.classList.add('custom-theme');
    });
});

You can custom the class CSS (custom-theme) with the values with you prefer

.custom-theme {
    background-color: green;
    color: white;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...