如何在JavaScript中将常数加到innerWidth?

l3l*_*lue 2 javascript css string-concatenation

我试图在JS中对innerWidthand 进行求和constant 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';
  }
Run Code Online (Sandbox Code Playgroud)

Jor*_*lez 6

因为您正在串联字符串

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

字符串只是一堆字符,没有数字值(实际上不是真的,但是让您容易理解)。拥有字符串var thing = '100';与拥有字符串具有相同的数字值var thing = 'asd';,即没有。

串联两个字符串可以得到串联结果,因此,"asd" + "zxc"结果为"asdzxc",就像您串联两个字符串的方式一样:"100" + "100"result为"100100"

为了使代码正常工作,只需删除字符串定界并求和实际数字,如下所示:

this.film.style.width = (window.innerWidth + 100) + 'px';
Run Code Online (Sandbox Code Playgroud)

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

  • @ l3lue,您好:如果有帮助,请考虑将其视为“可接受的”答案,以方便社区理解,谢谢 (2认同)