简体   繁体   中英

How to change the font of an element by clicking on another element with JavaScript?

I'm trying to create a style guide generator that would allow someone to select a font they want to use in their project. It would have a list of fonts to choose from and then when they click on the font they would want it'll change the h1 tag so they can preview the font selected

Here is a simple Snippet, that does what I think your after.

 const demo = document.querySelector("h1"); for (const a of document.querySelectorAll(".select-font")) a.onclick = () => { demo.style.fontFamily = a.style.fontFamily; } 
 .select-font { margin: 10px; padding: 10px; background-color: silver; cursor: pointer; display: inline-block; width: 100px; } h1 { margin: 10px; padding: 10px; background-color: yellow; } 
 <div>Click one of the fonts</div> <div class="select-font" style="font-family: Times New Roman, Times, serif"> Times</div> <div class="select-font" style="font-family: Arial, Helvetica, sans-serif"> Arial</div> <div class="select-font" style="font-family: 'Comic Sans MS', cursive, sans-serif"> Comic</div> <br> <h1>Demo</h1> 

You can just use font-family css property.

From javascript you can set it like this:

document.getElementById("preview_element").style.fontFamily = "arial"

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