You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中忽略'<rect>属性height无效负值(-64)'错误?

解决方案

首先,你写的try-catch代码存在语法错误——tnValue.toString()后面缺少了闭合的括号,这会导致代码无法被正确解析,所以try-catch完全起不到作用。

1. 修复语法后的基础try-catch

如果可以接受某一行报错后后续代码不执行,先补上缺失的括号即可:

try {
    tnBar.setAttribute("height", tnValue.toString()); // 补上闭合括号
    fnBar.setAttribute("height", fnValue.toString()); 
    tpBar.setAttribute("height", tpValue.toString());
    fpBar.setAttribute("height", fpValue.toString());
} catch(err){
    // 空代码块,忽略错误
}

2. 独立处理每个语句(互不影响)

如果希望即使某一行报错,其他行依然能正常执行,需要给每个setAttribute操作单独包裹try-catch:

try {
    tnBar.setAttribute("height", tnValue.toString());
} catch(err) {}

try {
    fnBar.setAttribute("height", fnValue.toString());
} catch(err) {}

try {
    tpBar.setAttribute("height", tpValue.toString());
} catch(err) {}

try {
    fpBar.setAttribute("height", fpValue.toString());
} catch(err) {}

3. 提前处理负值(从根源避免报错)

既然你预期会出现负值,更稳妥的方式是先把值转换为合法的非负数,避免触发报错:

// 把负值转为0,确保height属性值合法
const safeTnValue = Math.max(0, tnValue);
tnBar.setAttribute("height", safeTnValue.toString());

const safeFnValue = Math.max(0, fnValue);
fnBar.setAttribute("height", safeFnValue.toString());

const safeTpValue = Math.max(0, tpValue);
tpBar.setAttribute("height", safeTpValue.toString());

const safeFpValue = Math.max(0, fpValue);
fpBar.setAttribute("height", safeFpValue.toString());

内容的提问来源于stack exchange,提问作者throwCode4

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 17:10:33