无法通过 JavaScript 设置 div.style.left 和 div.style.top css 属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10351291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 09:34:39  来源:igfitidea点击:

Unable to set div.style.left and div.style.top css properties via JavaScript

javascriptcsshtmlcss-position

提问by Ramon Wenger

I ran in a very confusing problem today

我今天遇到了一个非常令人困惑的问题

I have a canvas, and a div, like this

我有一个画布和一个 div,就像这样

<canvas id="canvas" width="800" height="400"></canvas>
<div id="xy"></div>

I then set the properties of the div via a css file, e.g. position:absolute and display:none Then, i write the X/Y Position in the div via JS and try to set the properties of the div so that the div follows the mouse around, like this

然后我通过 css 文件设置 div 的属性,例如 position:absolute 和 display:none 然后,我通过 JS 在 div 中写入 X/Y 位置并尝试设置 div 的属性,以便 div 遵循鼠标四处走动,像这样

var div = document.getElementById("xy");
var x = e.pageX - this.offsetLeft - 1;
var y = e.pageY - this.offsetTop - y0 - 0.5;
div.style.display = "block";
div.style.left = e.pageX + 25;
div.style.top = e.pageY -10;
div.style.backgroundColor = "#f00";

The funny thing now is: i can set the display and backgroundColor without a problem, but the left and top properties don't work. If i delete my DOCTYPE-declaration in my HTML file though, i can modify the left and top properties without any trouble. Working without doctype is out of the question of course. Am i doing something that shouldn't be done or missing something completely obvious?

现在有趣的是:我可以毫无问题地设置 display 和 backgroundColor,但是 left 和 top 属性不起作用。如果我在 HTML 文件中删除我的 DOCTYPE 声明,我可以毫无困难地修改 left 和 top 属性。没有 doctype 的工作当然是不可能的。我是在做不应该做的事情还是遗漏了一些完全显而易见的事情?

回答by ke20

You have forgotten "px":

你忘记了“px”:

div.style.left = (e.pageX + 25) + 'px';
div.style.top = (e.pageY -10) + 'px';

You might also want to add div.style.position = "absolute";

您可能还想添加 div.style.position = "absolute";

If you think there's any chance that e.pageXor e.pageYwill be strings rather than numbers, throw a parseIntin:

如果您认为有可能e.pageXe.pageY将是字符串而不是数字,请parseInt输入:

div.style.left = (parseInt(e.pageX, 10) + 25) + 'px';
div.style.top = (parseInt(e.pageY, 10) - 10) + 'px';

回答by Eralper

Another method for setting style properties like DIV objects is using the setProperty method

设置样式属性(如 DIV 对象)的另一种方法是使用 setProperty 方法

You can check below Javascript code sample

您可以查看以下 Javascript 代码示例

document.getElementById('div').style.setProperty("top","100px");

回答by Kulbhushan Chaskar

I also faced same problem, but when I added a space into the empty div, it started positioning properly. i.e.

我也遇到了同样的问题,但是当我在空的 div 中添加一个空格时,它开始正确定位。IE

div.innerHTML = &nbsp;&nbsp;