通过javascript在每次点击时动态增加字体大小

Increasing font size dynamically on every click through javascript

本文关键字:增加 动态 字体 javascript 通过      更新时间:2023-09-26

我正在努力找出一种方法,通过我可以动态地增加所需元素的字体大小,下面是代码:

<!DOCTYPE html>
<html>
<head>
<style>
.example {
    border: 1px solid black;
    margin: 5px;
}
</style>
</head>
<body>
<div class="example">
A div with class="example"
</div>
<div class="example">
Another div with class="example"
</div>
<p>This is a p element with class="example".</p>
<p>This is a <span class="example">span</span> element with                Class="example" inside another p element.</p>
<p>Click the button to change the background color of all elements with class="example".</p>
<button class="example" onclick="myFunction()">Try it</button>

<script>
function myFunction() {
    var x = document.getElementsByClassName("example");
    var i;
    for (i = 0; i < x.length; i++) {
        x[i].style.fontSize = "xx-large";
}
}
</script>
</body>
</html>

现在,问题是,当我点击按钮时,突出显示元素的字体大小增加了,但是当我再次点击按钮时,样式保持不变,例如在点击fontsize = 12px之前,点击后它变成了24px,此时我希望当我再次点击按钮时尺寸进一步增加,请帮助!

目前你的函数只做x[i].style.fontSize = "xx-large";,这意味着"设置字体大小为xx-large",而不是"增加字体大小"。

您应该获得x[i].style.fontSize的值,并写入一个新的增加值(可能以像素为单位)。

如果你想每次增加*2的font-size,请这样做:

for (i = 0; i < x.length; i++) {
    x[i].style.fontSize = ( parseInt( x[i].style.fontSize ) * 2 ) + 'px';