[英]Increase and decrease font size not working with all paragraphs javascript
[英]How to change font size of all paragraphs in div with Javascript?
我正在嘗試根據屏幕大小更改 div 中所有段落的字體大小和行高 - 以實現移動響應。 正如您在示例中看到的,當我嘗試使用 JS 更改段落大小時,它只會更改第一個元素。 當我在 CSS 中執行此操作時,它可以工作,而不是 JS。
const textContP = document.querySelector('.textcont p'); textContP.setAttribute("style", "line-height: 5vw"); textContP.style.fontSize = "3vw";
.textcont p { font-size: 4vw; line-height: 5vw }
<div class="textcont"> <p>test</p> <p>test2</p> </div>
問題是document.querySelector()
。 它只選擇找到的第一個元素。 您需要使用document.querySelectorAll()
來獲取所有<p>
標簽。
document.querySelectorAll('.textcont p').forEach(p => { p.style.lineHeight = "5vw"; p.style.fontSize = "3vw"; })
.textcont p { font-size: 4vw; line-height: 5vw }
<div class="textcont"> <p>test</p> <p>test2</p> </div>
使用querySelectorAll
而不是querySelector
。
const textContP = document.querySelectorAll('.textcont p'); textContP.setAttribute("style", "line-height: 5vw"); textContP.style.fontSize = "3vw";
.textcont p { font-size: 4vw; line-height: 5vw }
<div class="textcont"> <p>test</p> <p>test2</p> </div>
querySelector
只選擇第一個元素。 所以使用querySelectorAll
這會將所有選定的元素放入一個數組中,然后您可以使用for loop
或for each
循環遍歷數組以更改所有元素。
注意:確保為所有元素提供相同的 class。 並確保添加點.
當您在選擇器中添加類時
在此處了解有關循環的更多信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.