我在这里读到一个问题,试图得到文本的字体大小。他们给出的答案是用一种测量方法得到像素大小。我想要做的就是得到字体大小值,这样我就可以更改它了。
例如:
var x = document.getElementById("foo").style.fontSize;
document.getElementById("foo").style.fontSize = x + 1;虽然这两个例子都起作用,但是这个示例不起作用。
document.getElementById("foo").style.fontSize = "larger";document.getElementById("foo").style.fontSize = "smaller";唯一的问题是它只更改了一次大小。
发布于 2013-03-04 05:48:05
仅仅抓取元素的style.fontSize可能不起作用。如果font-size是由样式表定义的,这将报告"" (空字符串)。
您应该使用window.getComputedStyle。
var el = document.getElementById('foo');
var style = window.getComputedStyle(el, null).getPropertyValue('font-size');
var fontSize = parseFloat(style);
// now you have a proper float for the font size (yes, it can be a float, not just an integer)
el.style.fontSize = (fontSize + 1) + 'px';发布于 2013-03-04 05:53:44
如果您的元素没有字体大小属性,则代码将返回空字符串。您的元素没有必要具有字体大小属性。元素可以从父元素继承属性。
在这种情况下,您需要找到计算的字体大小。试试这个(不确定IE)
var computedFontSize = window.getComputedStyle(document.getElementById("foo")).fontSize;
console.log(computedFontSize);变量computedFontSize将以单位的字体大小返回。单位可以是px,em,%。您需要去掉该单元来执行算术操作并分配新值。
发布于 2013-03-04 05:48:50
如果您使用的是Jquery,则以下是解决方案。
var fontSize = $("#foo").css("fontSize");
fontSize = parseInt(fontSize) + 1 + "px";
$("#foo").css("fontSize", fontSize );希望这能成功。
https://stackoverflow.com/questions/15195209
复制相似问题