简体   繁体   中英

How to change background color and font color on click (no jQuery)?

I'm working on an eReader-like project for school and I was instructed to not to use jQuery.

I want to allow users to change the colors of the page based on their preferences. I figured how to change the background-color by using color names in the class of the buttons, but I can't figure how to change the font color (something I really need to do specifically for the black background).

Any help would be appreciated!

HTML:

<div class="textBox">Dummy text</div>
<button class="bisque">sepia</button>
<button class="black">black</button>
<button class="white">white</button>    

JS:

var elems = document.getElementsByTagName('button');

for(var i = 0; i < elems.length; i++) {
     elems[i].onclick = function(e) {
       e.preventDefault();
       var color = this.getAttribute('class');
       document.getElementsByTagName('body')[0].style.background = color;
   }
};

You can change the font color doing the following:

 var elems = document.getElementsByTagName('button'); for(var i = 0; i < elems.length; i++) { elems[i].onclick = function(e) { e.preventDefault(); var color = this.getAttribute('class'); var font_color = this.getAttribute('data-color'); document.getElementsByClassName('textBox')[0].style.color = font_color; document.getElementsByTagName('body')[0].style.background = color; } }; 
 <div class="textBox">Dummy text</div> <button class="bisque" data-color="black">sepia</button> <button class="black" data-color="white">black</button> <button class="white" data-color="bisque">white</button> 

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