最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

for loop - increase font size iteratively using javascript - Stack Overflow

programmeradmin0浏览0评论
var text = document.querySelector('p')
for(var i=10px; i<=40px; i++)
  text.style.fontSize = i; 

I want a script which increases the font size in every iteration of the for-loop. The above code is the prototype of my requirement (which won't work since pixels can't be assigned to a variable). Help me providing the correct code.

var text = document.querySelector('p')
for(var i=10px; i<=40px; i++)
  text.style.fontSize = i; 

I want a script which increases the font size in every iteration of the for-loop. The above code is the prototype of my requirement (which won't work since pixels can't be assigned to a variable). Help me providing the correct code.

Share Improve this question asked Mar 31, 2018 at 7:23 SuryaSurya 1,0914 gold badges18 silver badges33 bronze badges 3
  • There is no 10px literal. – Jonas Wilms Commented Mar 31, 2018 at 7:25
  • Is the number of you p tags dynamically or fixed? – Luckyfella Commented Mar 31, 2018 at 7:29
  • Just wonder if you have 1 p tag and want to increase only that one like an animation or if you want to have every p tag with higher font size. – Luckyfella Commented Mar 31, 2018 at 7:33
Add a ment  | 

4 Answers 4

Reset to default 3

You probably want to use setTimeout recursion instead, so the text doesn't increase in size instantly:

var text = document.querySelector('p');

function increaseTextSize(size) {
  text.style.fontSize = size + 'px'; 
  if (size <= 40) setTimeout(increaseTextSize, 50, size + 1);
}
increaseTextSize(10);
<p>my text</p>

You can also try out this demo using CSS transition effect:

// After 500ms change the font from 10 to 60px
// and css will take care of the rest
setTimeout(() => {
  var text = document.querySelector('p');
  text.style.fontSize = '60px';
  text.style.color = 'blue';  // <-- you can also add color effects, if you want
}, 500);
p {
  font-size: 10px;
  color: red;
  -webkit-transition: all 2.5s ease;
  -moz-transition: all 2.5s ease;
  -o-transition: all 2.5s ease;
  -ms-transition: all 2.5s ease;
}
<p>Hello World!</p>

var text = document.querySelector('p')

for (var i = 10; i <= 40; i++) {
  text.style.fontSize = `${i}px`;
}

You cannot append px in the loop since it has to be an integer.

var text = document.querySelector('p');

function increaseTextSize(size) {
  text.style.fontSize = size + 'px'; 
  if (size <= 40) setTimeout(increaseTextSize, 50, size + 1);
}
increaseTextSize(10);
<p>my text</p>

Dfhg

发布评论

评论列表(0)

  1. 暂无评论