对象样式特性值的数据类型

Data type of object style property value

本文关键字:数据类型 样式 对象      更新时间:2023-09-26

考虑一下:

var input = document.getElementById('input'),
  khaki = document.getElementById('khaki'),
  dataType = document.getElementById('dataType');
input.oninput = function() {
  khaki.style.flexGrow = 10 - this.value;
  dataType.textContent = 'Data type: ' + typeof khaki.style.flexGrow;
};
main {
  width: 400px;
  height: 100px;
  border: 1px solid #C3C3C3;
  display: flex;
}
main div {
  flex-grow: 1;
}
<main>
  <div style="background-color:coral;"></div>
  <div style="background-color:lightblue;"></div>
  <div style="background-color:khaki;" id="khaki"></div>
  <div style="background-color:pink;"></div>
  <div style="background-color:lightgrey;"></div>
</main>
<input type="number" id="input" value="9" max="9">
<span id="dataType"></span>

我想知道为什么它将flex行属性值的数据类型显示为string,但如果将khaki.style.flexGrow替换为等效的10 - this.value:

dataType.textContent = 'Data type: ' + typeof (10 - this.value);

它将把数据类型显示为CCD_ 4
我可以概括它并得出结论,所有对象样式的属性值和所有元素的属性值都是字符串吗?

是的,所有样式(或重要的所有属性)都存储为字符串。由于所有样式都存储在一个字符串中,然后将该字符串解析为各个样式。

仅仅因为10-"1"9,即操作数10"1"都先转换为数字,然后进行减法运算,这就是为什么结果是数字9

但CCD_ 10本身就是CCD_

如果简而言之-因为你要从一个数字中减去一个字符串。根据减法运算器算法,两个操作数都被转换为数字。

1. Let lref be the result of evaluating AdditiveExpression.
2. Let lval be GetValue(lref).
3. Let rref be the result of evaluating MultiplicativeExpression.
4. Let rval be GetValue(rref).
5. Let lnum be ToNumber(lval). //conversion of 10 to number
6. Let rnum be ToNumber(rval). //conversion of this.value (e.g. "1") string to number
7. Return the result of applying the subtraction operation to lnum and rnum.