3 回答

TA貢獻1946條經驗 獲得超4個贊
僅抓住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';

TA貢獻1860條經驗 獲得超9個贊
如果您的元素沒有font-size屬性,則代碼將返回空字符串。您的元素不必具有font-size屬性是不必要的。元素可以從父元素繼承屬性。
在這種情況下,您需要找到計算出的字體大小。試試這個(不確定IE)
var computedFontSize = window.getComputedStyle(document.getElementById("foo")).fontSize;
console.log(computedFontSize);
變量calculatedFontSize將返回帶有單位的字體大小。單位可以是px,em,%。您需要剝離單元進行算術運算并分配新值。

TA貢獻1779條經驗 獲得超6個贊
您從fontSize獲得的值類似于“ 12px”或“ 1.5em”,因此在該字符串上加1將得到“ 12px1”或“ 1.5em1”。您可以使用字體大小并使用以下命令對其進行操作:
var fontSize = parseInt(x);
fontSize = fontSize + 1 + "px";
document.getElementById("foo").style.fontSize = fontSize;
添加回答
舉報