如何在 JavaScript 中将常量求和到 innerWidth?

How do I sum constant numbers to innerWidth in JavaScript?

我试图在 JS 中对 innerWidthconstant numbers 求和,但浏览器一直只是附加这些数字,而不是计算。

奇怪的是给负值工作正常。仅当我尝试将数字相加为 innerWidth.

时,浏览器才会计算

有什么办法可以解决这个问题吗?

  Slider.prototype.sizeReseting = function(event) {
    this.frame.style.height = (window.innerWidth - '300') + 'px';
    this.frame.style.width = (window.innerWidth - '300') + 'px';
    this.film.style.height = (window.innerWidth - '400') + 'px';
    this.film.style.width = (window.innerWidth + '100') + 'px';
  }

因为你是concatenating strings.

在JavaScript中,字符串定义在引号或双引号之间。因此 var thing = 100; 是一个数字,而 var thing = '100'; 是一个字符串。

字符串只是一串字符,没有数值(实际上不是这样,但为了让您轻松理解)。字符串 var thing = '100'; 与字符串 var thing = 'asd'; 具有相同的数值,即 none.

连接两个字符串会得到连接结果,因此 "asd" + "zxc" 会导致 "asdzxc",就像连接两个字符串一样:"100" + "100" 会导致 "100100".

要让您的代码正常工作,只需删除字符串定界并对实际数字求和,如下所示:

this.film.style.width = (window.innerWidth + 100) + 'px';

请注意我是如何删除 100 周围的单引号以使其成为实际数字的。

解释:

这两行有非常不同的结果:

this.film.style.height = (window.innerWidth - '400') + 'px';
this.film.style.width = (window.innerWidth + '100') + 'px';
  • 在第一个中,符号 - 将您的刺 400 转换为数字。因此,您要减去 400 到window.innerWidth 的值(然后添加字符串'px')

  • 在第二个中,符号 + 充当 concatenation operator。因此,您 连接 window.innerWidth + 字符串 '100' + 字符串 'px'.

    的结果

解决方案:

只需从您的代码中删除单引号:

this.film.style.width = (window.innerWidth + 100) + 'px';