简体   繁体   English

分配给element.style时,为什么元素的样式没有更改?

[英]Why isn't my element's style changing when I assign to element.style?

I'm trying to write an event listener that moves an element where I move my mouse, by setting properties of the CSSStyleDeclaration object on the element: 我正在尝试编写一个事件侦听器,该事件侦听器通过在元素上设置CSSStyleDeclaration对象的属性来将元素移动到鼠标移动的位置:

var overlay = document.getElementById('overlay');
document.body.addEventListener('mousemove',function moveOverlay(evt){
  overlay.style.left = evt.clientX;
  overlay.style.top = evt.clientY;
});

However, after each assignment to a property of style runs, the value (as checked in the debugger) doesn't change - it remains the default empty string value '' . 但是,在对style属性的每次赋值运行之后,值(在调试器中检查)不会改变-它仍然是默认的空字符串值'' A change like overlay.style.color = 'blue' works - what am I doing wrong? overlay.style.color = 'blue'这样的更改有效-我在做什么错?

CSS style rules will only be assigned as a property value if they are syntactically valid - if the prospective value is invalid for the CSS rule in question, the operation will be ignored. 如果CSS样式规则在语法上有效,则仅将其分配为属性值-如果该CSS规则的预期值无效,则将忽略该操作。 Numbers for CSS properties need a unit suffix to be valid - in this case, it needs to be specified that the positions are in pixels . CSS属性的数字需要有效的单位后缀-在这种情况下,需要指定位置以像素为单位 Try evt.clientX + 'px' instead. 请尝试evt.clientX + 'px'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM