使用 javascript 迭代增加字体大小
increase font size iteratively using javascript
var text = document.querySelector('p')
for(var i=10px; i<=40px; i++)
text.style.fontSize = i;
我想要一个在 for 循环的每次迭代中增加字体大小的脚本。上面的代码是我的要求的原型(因为不能将像素分配给变量,所以它不起作用)。帮我提供正确的代码。
var text = document.querySelector('p')
for (var i = 10; i <= 40; i++) {
text.style.fontSize = `${i}px`;
}
您不能在循环中追加 px
,因为它必须是整数。
您可能想改用 setTimeout 递归,这样文本的大小不会立即增加:
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>
您也可以使用 CSS 过渡效果试用此演示:
// 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=10px; i<=40px; i++)
text.style.fontSize = i;
我想要一个在 for 循环的每次迭代中增加字体大小的脚本。上面的代码是我的要求的原型(因为不能将像素分配给变量,所以它不起作用)。帮我提供正确的代码。
var text = document.querySelector('p')
for (var i = 10; i <= 40; i++) {
text.style.fontSize = `${i}px`;
}
您不能在循环中追加 px
,因为它必须是整数。
您可能想改用 setTimeout 递归,这样文本的大小不会立即增加:
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>
您也可以使用 CSS 过渡效果试用此演示:
// 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>