簡體   English   中英

增加和減少字體大小不適用於所有段落 javascript

[英]Increase and decrease font size not working with all paragraphs javascript

**I have many separated paragraphs in one HTML page all of them have the same id **id=text** when I use the onmousemove event only the first paragraph can increase and decrease the font size not all of them although they have the same id  .** 

這是 javascript 代碼:

function incfont(){
    var t= document.getElementById('fontsize').value;
    var x= document.getElementById('text');
    x.style.fontSize = t+"px";

**這里是具有相同 id 的段落示例 **

<p id="test">paragraph 1 </p>
<p id="test">paragraph 2 </p>

由於您有很多段落,因此您不應設置 id,而應設置 class。

getElementById() 只獲取一個元素。

請參考這個問題和選擇的答案。 GetElementByID - 多個 ID

在 Html

<p class="test">paragraph 1 </p>
<p class="test">paragraph 2 </p>

在腳本中

function incfont(){
    var t= document.getElementById('fontsize').value;
    var x= document.getElementsByClassName("test");
    for(var i=0;i<x.length;i++){
    x[i].style.fontSize = t+"px";
    }
}

在 Html

//Instead of Id use class in HTML
<p class="test">paragraph 1 </p>
<p class="test">paragraph 2 </p>

在腳本中

function incfont(){
    var t= document.getElementById('fontsize').value;
    //Here you need to change getElemetById to getElementsByClassName because getElementById() only gets a single element
    var x= document.getElementsByClassName("test");
    x.style.fontSize = t+"px";
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM