[英]How do I start a script for a button in HTML to change font size?
我不確定如何啟動一個在單擊按鈕時設置字體大小的腳本。 我應該有一個標記為正常、中等和大的按鈕。
有幾種方法可以更改 HTML 實體的屬性:
通過 HTML 中的onclick
屬性:
<button onclick="func()">Text</button>
通過 HTML 代碼中的id
或class
屬性:
<button id="btnId">Text</button>
<button class="btnClass">Text</button>
以及以下 JavaScript 代碼 -
對於 id 元素:
let btn_with_id = document.getElementById("btnId") // Getting element with specific id btn_with_id.onclick = () => { btn_with_id.style.fontSize = "55px" // Can be anything: em, % etc. }
對於多個類元素(如果您想更改多個項目):
let btns_with_className = document.getElementsByClassName("btnClass") // Getting elements with the same class for (let btn of btns_with_className) { btn.onclick = () => btn.style.fontSize = "55px" }
我們也可以添加帶有一些預制屬性的 className btn_with_id.classList.add("btnCustomClass")
另外還有一種onclick事件的方式addEventListener()
這是它的工作原理:
btn_with_id.addEventListener('click', event => { btn_with_id.classList.add("Your_class") })
如果要根據font-size
更改按鈕文本,這里是解決方案:
if (btn_with_id.style.fontSize == "55px") btn_with_id.innerHTML = "Large" // Here can be different `fontSize` and `innerHTML` text
改變字體大小的按鈕:
<button type="button" onclick="document.body.style.fontSize = '12px';">Small</button>
<button type="button" onclick="document.body.style.fontSize = '16px';">Normal</button>
<button type="button" onclick="document.body.style.fontSize = '20px';">Large</button>
這會在 body 元素上設置字體大小,因此其他具有自己字體大小設置的元素不會改變,除非您使用em
或rem
作為大小單位。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.