嗨,有沒有辦法使附加的“YAY”與“我很高興”文本具有不同的風格?例如。更大的字體大小/粗體。
document.getElementById("appendButton").onclick = function() {
document.getElementById("happy").innerHTML = " YAY";
}
<p id="happy">I am happy</p>
<button id="appendButton">Click here to cheer!</button>
我試圖給它一個帶有跨度的 id,但是按鈕不會附加任何東西。將不勝感激任何幫助謝謝!
uj5u.com熱心網友回復:
您將無法使用 id,因為 id 必須是唯一的(這意味著您不能在一個頁面上擁有多個并期望正確的輸出)。
添加一個類。
注 1:我在addEventListener這里使用了更現代的方法。
注意 2:還值得一提的是,將 HTML 字串連接到innerHTML 被認為是不好的做法。insertAdjacentHTML是更好的選擇。
const button = document.getElementById('appendButton');
const happy = document.getElementById('happy');
button.addEventListener('click', handleClick, false);
function handleClick() {
happy.innerHTML = '<span > YAY</span>';
}
.yay { color: blue; font-weight: 600; }
<p id="happy">I am happy</p>
<button id="appendButton">Click here to cheer!</button>
uj5u.com熱心網友回復:
您可以span使用類附加元素,然后使用 CSS 對其進行樣式設定:
document.getElementById("appendButton").onclick = function() {
document.getElementById("happy").innerHTML = "<span class='large'>YAY</span>";
}
.large{
font-size:20px;
font-weight:bold;
}
<p id="happy">I am happy</p>
<button id="appendButton">Click here to cheer!</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/360685.html
標籤:javascript html
