[英]Positioning an element via javascript
I'm trying to position an element by percentage but it didn't work out for me, it worked only when I used pixels. 我正在尝试按百分比定位元素,但对我来说却没有用,仅当我使用像素时才起作用。
Here is my code: 这是我的代码:
var x=document.getElementById("fir")
x.style.position = "absolute";
x.style.left = 10%
x.style.top = 10%
If I assigned to x.style.left
any number followed by nothing it works fine but if I put percentage after the number like it's shown in the code above it doesn't work. 如果我将
x.style.left
分配x.style.left
任何数字,然后x.style.left
任何数字,则可以正常工作,但是如果我将百分比放在数字上面,如上面代码中所示,则它不起作用。 Any ideas on how can I use the percentage to position this element? 关于如何使用百分比定位此元素的任何想法?
Those values are supposed to be strings: 这些值应该是字符串:
x.style.left = '10%';
x.style.top = '10%';
Otherwise, the %
sign is interpreted as the remainder operator , leading to unexpected results or syntax errors (depending on your use of semicolons). 否则,
%
符号将被解释为余数运算符 ,从而导致意外的结果或语法错误(取决于分号的使用)。
You'd have to assign it as a string. 您必须将其分配为字符串。 You're syntax is invalid, because
10%
means something in JavaScript, so it's actually parsing x.style.left = 10%x.style.top = 10%
since JS ignores whitespace. 您的语法无效,因为
10%
在JavaScript中有含义,因此实际上是在解析x.style.left = 10%x.style.top = 10%
因为JS会忽略空格。
Like bfavaretto said, you need to assign the values as strings: 就像bfavaretto所说的那样,您需要将值分配为字符串:
x.style.left = '10%';
x.style.top = '10%';
and make sure you add your semicolons. 并确保添加分号。 :)
:)
The %
is CSS syntax, not javascript syntax and you need to wrap it in quotes: %
是CSS语法,而不是javascript语法,您需要将其用引号引起来:
var x=document.getElementById("fir")
x.style.position = "absolute";
x.style.left = "10%";
x.style.top = "10%";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.