javascript - 从比较 getComputedStyle().width 值的函数返回意外的真值

标签 javascript

我有以下功能

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/

相关文章:

javascript - 返回存在于全局范围内的变量的最佳实践?

javascript - HTML 表单 - 当我按下回车键时它会刷新页面!

javascript - 没有节点的Vue SSR

javascript - 为什么在扩展对象时使用 Object.create 作为原型(prototype)?

javascript - Javascript .then() 函数检查 Web api 中的 Promise

javascript - 无法对超过 9 个输入 javascript 求和

javascript - 使用自定义对话框时如何关闭引导箱

javascript - location.href 不改变 iframe src

javascript - 禁用 .node_repl_history 文件

javascript - 在页面加载时显示弹出窗口,然后定期显示和隐藏它