原生JavaScript样式语法

时间:2011-07-03 08:12:57

标签: javascript css

我正在研究一些原生JavaScript(根本不是我的强项......)并没有看到我的功能结果。我确定我在某处有语法错误。你能帮我识别一下吗?仅供参考 - 该功能将动态居中页面上的对象。

this.style[left]= ((windowWidth - this.style[width])/2);
this.style[top]= ((windowHeight - this.style[height])/2);

4 个答案:

答案 0 :(得分:5)

至少有三个问题。

首先:CSS heightwidthlefttop属性采用长度。您正在传递数字

您必须包含一个单元。

同样,您需要考虑宽度和高度值的单位。

第二:你还需要平衡你的括号。

第三:使用方括号表示法时,需要传入字符串。目前,我认为lefttopundefined

this.style.left = (windowWidth  - parseInt(this.style.width,10)) / 2  + 'px';
this.style.top  = (windowHeight - parseInt(this.style.height,10)) / 2 + 'px';

最后,只有在元素的宽度和高度使用内联样式定义时(或者如果这些属性是通过JavaScript设置的),这才有效。否则,您尝试阅读的值将为undefined。在这种情况下,您需要处理computed style

另请注意,除非元素为positioned,否则topleft将无效。

答案 1 :(得分:1)

您省略了(

this.style [left] =((windowWidth - this.style [width])/ 2);

this.style [top] = (windowHeight - this.stylep [height])/ 2);

答案 2 :(得分:0)

您还错过了第二行的开场(。除此之外,假设您使用的所有变量都已定义,您的代码似乎没问题。

this.style[left] = ((windowWidth - this.style[width]) / 2);
this.style[top] = ((windowHeight - this.style[height]) / 2);

这也可以这样写:

this.style.left = ((windowWidth - this.style.width) / 2);
this.style.top = ((windowHeight - this.style.height) / 2);

答案 3 :(得分:0)

设置样式时,您应该有一个单位,例如100px而非100

在阅读样式时,它将有一个单位,因此您需要使用parseInt函数对其进行解析,以获得单位前面的数字。

使用括号访问属性时,应使用字符串,而不是标识符:

this.style["left"] = ((windowWidth - parseInt(this.style["width"],10)) / 2) + "px";
this.style["top"] = ((windowHeight - parseInt(this.style["height"],10)) / 2) + "px";

您还可以使用.运算符访问属性:

this.style.left = ((windowWidth - parseInt(this.style.width,10)) / 2) + "px";
this.style.top = ((windowHeight - parseInt(this.style.height,10)) / 2) + "px";