简体   繁体   English

如何通过使用JavaScript单击另一个元素来更改元素的字体?

[英]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 它会有一个字体列表供您选择,然后当他们单击该字体时,他们希望它会更改h1标签,以便他们可以预览所选的字体

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. 您可以只使用font-family css属性。

From javascript you can set it like this: 从javascript,您可以这样设置:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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