增加字体大小的onclick事件

问题描述 投票:0回答:3

在新的JS中,我想了解如何简单地增加文本的字体大小。我的目标是点击文本并看到它增加。

我尝试过类似的尝试但没有成功:

function increaseFontSize(objId) {
    obj = document.getElementById(objId);
    //get current font size of obj
    currentSize = parseFloat(obj.style.fontSize); //parseFloat gives you just the numerical value, i.e. strips the 'em' bit away
    obj.style.fontSize = (currentSize + .1) + "em";
}

我希望看到带有新JS的演示,例如querySelector,否则将解决此简单问题,使我能够学习正确的方法。

javascript
3个回答
1
投票

获得元素的font-size(带有getComputedStyle.getPropertyValue),将其增加,然后再次将其分配给元素:

getComputedStyle.getPropertyValue
document.getElementById('myText').addEventListener("click", function () {
  let fontSize = parseInt(window.getComputedStyle(this, null).getPropertyValue('font-size'));
  fontSize++;
  this.style.fontSize = fontSize + 'px';
});

1
投票

元素的<div id="myText">My text</div>属性仅返回在HTML的style属性上设置的样式信息。如果通过style或JavaScript设置了style,则将获得class。而是使用undefined,它将返回当前样式信息,而不管它如何设置。

getComputedValue()
// Instead of the function only being able to work when an element
// id is passed to it, have the function work as long as an element
// reference itself is passed to it. This is more flexible, since
// not all elements will have an id.
function increaseFontSize(element) {
    currentSize = parseFloat(getComputedStyle(element).fontSize); 
    console.log("Original size of: " + element.nodeName + ": " + currentSize);
    element.style.fontSize = 1.1 + "em";
    console.log("New size of: " + element.nodeName + ": " + getComputedStyle(element).fontSize);
}

increaseFontSize(document.querySelector("p"));
increaseFontSize(document.querySelector("div.someClass"));
increaseFontSize(document.querySelector("h1"));

0
投票

您想要执行以下操作。

<p>A long time ago</p>
<div class="someClass">In a galaxy far far away</div>
<h1>STAR WARS</h1>
function updateFontSize() {
  const p = document.querySelectorAll('p')[0];
  const style = window.getComputedStyle(p, null).getPropertyValue('font-size');
  const fontSize = parseFloat(style);
  p.style.fontSize = (fontSize + 10) + 'px';
}
© www.soinside.com 2019 - 2024. All rights reserved.