我有以下功能
const wider_than = (el1, el2) => getComputedStyle(el1).width > getComputedStyle(el2).width;
我用它来控制嵌套 div 的 innerhtml 值。如果内部 div 比外部 div 宽,我希望内部 div 将其文本设置为“错误”。否则我想将其设置为用户定义的值。
但是函数在意想不到的时候返回真值。使用以下日志
console.log(getComputedStyle(display_text).width);
console.log(getComputedStyle(display).width);
console.log(wider_than(display_text, display));
console.log(getComputedStyle(display_text).width > getComputedStyle(display).width);
并逐个字符更新 display_text innerHTML 的值,第一个字符正常运行,但第二个字符中断。这是日志的输出
53.3958px
639px
false
false
80.0625px
639px
true
true
谁能解释为什么会这样?
最佳答案
console.log('"b" > "a" :', "b" > "a");//"b" comes after "a"
console.log('"bun" > "abbot" :', "bun" > "abbot");//"b" comes after "a" regardless of word length
console.log('"2" > "1" :', "2" > "1");
console.log('"2" > "100" :', "2" > "100");
字符串不能像数字一样排序是有充分理由的 - 假设您有一个播放列表并试图对歌曲标题进行排序,Arctic Monkeys 的 “7” 应该排在 之后滚石乐队的第 19 次神经衰弱”。
parseFloat
global 函数专门用于从以数字开头的字符串中提取数字。所以它非常适合像“53.3958px”这样的尺寸值
const size1 = "53.3958px";
const size2 = "639px";
const size3 = "80.0625px";
console.log(`${size1} > ${size2} compared as strings:`, size1 > size2);
console.log(`${size1} > ${size2} compared as numbers:`, parseFloat(size1) > parseFloat(size2));
console.log(`${size3} > ${size2} compared as strings:`, size3 > size2);
console.log(`${size3} > ${size2} compared as numbers:`, parseFloat(size3) > parseFloat(size2));
关于javascript - 从比较 getComputedStyle().width 值的函数返回意外的真值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52899036/