gpt4 book ai didi

javascript - parseFloat 返回 NaN (解析文档样式大小时)

转载 作者:行者123 更新时间:2023-11-28 19:28:44 25 4
gpt4 key购买 nike

当我在 console.log 中打印它时,正文样式 parseFloat 一直返回 NaN,而它应该是 -0.1 或 0.1,我很可能只是累了,但我看不到问题。一如既往,我们非常感谢任何帮助,也不是在这里寻找 jQuery 答案,这必须是 JS

function startUp() {
var fontButtons = document.getElementsByClassName("fontsizer");
for (var i=0; i < fontButtons.length; i++) {
document.getElementsByClassName("fontsizer")[i].addEventListener("click", resizeText);
}
};

window.onload = startUp;

function resizeText() {
var fontChange = parseFloat(this.value);
console.log(fontChange);
if (document.body.style = "") {
document.body.setAttribute("style", "font-size:1.0em;");
}
var currentFontSize = parseFloat(document.body.style.fontSize.replace('em', ''));
console.log(currentFontSize);
document.body.style.fontSize = (currentFontSize + fontChange) + "em";
};

和 html

<div id="fontbuttons">
<input class="fontsizer" value="-0.1" type="image" id="fontdown" alt="-" src="fontdown.png" />
<input class="fontsizer" value="0.1" type="image" id="fontup" alt="+" src="fontup.png" />
</div>

最佳答案

1 = 是赋值,所以这一行实际上意味着明确的正文样式。

if (document.body.style = "") {

然后它将分配的值(空字符串)返回给 if 语句,而 "" 是一个假值,因此检查实际上是 if (假){...。您永远不会设置字体大小。

您应该使用=====来比较

if (document.body.style == "") {

2 document.body.style 是一个对象,它永远不应该等于空字符串。您应该将 document.body.style.fontSize 与它进行比较。

3 使用 document.body.style.fontSize = "1.0em" 而不是 document.body.setAttribute。因为setAttribute只改变HTML属性,而你想要的是DOM属性。

EDIT: I missed a thing, as pointed out by Roko C. Buljan. When you set font size in CSS, document.body.style.fontSize will still be emtpy string, unless you manipulate it with JS. You'd better compare with computed style, the solution is addressed in his answer.

function startUp() {
var fontButtons = document.getElementsByClassName("fontsizer");
for (var i = 0; i < fontButtons.length; i++) {
fontButtons[i].addEventListener("click", resizeText);
}
};

window.onload = startUp;

function resizeText() {
var fontChange = parseFloat(this.value);
console.log(fontChange);

if (document.body.style.fontSize == "") {
document.body.style.fontSize = "1.0em";
}

var currentFontSize = parseFloat(document.body.style.fontSize.replace('em', ''));
console.log(currentFontSize);
document.body.style.fontSize = (currentFontSize + fontChange) + "em";
};
<div id="fontbuttons">
<input class="fontsizer" value="-0.1" type="button">
<input class="fontsizer" value="0.1" type="button">
</div>
<p>text</p>

关于javascript - parseFloat 返回 NaN (解析文档样式大小时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27307486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com