尝试在typescript中为CSS分配值无效

尝试在typescript中为CSS分配值无效,css,typescript,Css,Typescript,我有一个脚本,它接受一个HtmleElement和一个拒绝在TypeScript中设置属性的元素的css.top和css.marginLeft 这是我的密码: let moveable1: HTMLElement = document.getElementsByClassName('moveable1')[0] as HTMLElement; 下面是我获取值并尝试设置属性的方法 console.log("**style.top** = " + (moveable1.style.top = S

我有一个脚本,它接受一个HtmleElement和一个拒绝在TypeScript中设置属性的元素的css.top和css.marginLeft

这是我的密码:

let moveable1: HTMLElement = document.getElementsByClassName('moveable1')[0] as HTMLElement;
下面是我获取值并尝试设置属性的方法

console.log("**style.top** = " + (moveable1.style.top = 
String((+this.chatScrollTop + +this.boxScrollTop).toFixed(0))));
console.log("**style.marginLeft** = " + (moveable1.style.marginLeft = String((+this.chatScrollLeft + +this.boxScrollLeft).toFixed(0))));

moveable1.style.top = String(moveable1.style.top);
moveable1.style.marginLeft = String(moveable1.style.marginLeft);
正在发生的是:

moveable1.style.marginLeft和moveable1.style.top始终相等

我不明白

控制台日志报告了正确的值

style.top = 69
style.marginLeft = 100
top: **<<<=== "EMPTY"** and should be 69
marginLeft: **<<<=== "EMPTY"** and should be 100

谢谢你,泽

将样式属性设置为数字,然后尝试重新读取并将其转换为字符串。这不管用;top等人不能是数字,因此它们保持在以前的值

此外,在设置样式时需要使用单位px、pt等,否则即使是字符串也无法设置。因此,当您尝试将它们从数字转换为字符串时,会得到另一个空白字符串

// This returns 1
console.log(document.body.style.top = 1);

// Nevertheless, it didn't work, since this returns ""
console.log(document.body.style.top);
这不是一个TypeScript问题,而是一个JavaScript问题,一个DOM问题

我的建议是简化这段代码。它不仅仅很难阅读,它做了很多不应该做的事情——不必要的转换,取决于作业的副作用,等等

像这样的方法应该会奏效:

const top = this.chatScrollTop + this.boxScrollTop;
const marginLeft = this.chatScrollLeft + this.boxScrollLeft;

moveable1.style.top = top.toFixed(0) + "px";
moveable1.style.marginLeft = marginLeft.toFixed(0) + "px";

您需要添加一个单元才能使其有效。chatScrollTop、boxScrollTop等是否作为字符串提供?那里有太多的转换,其中一些保证是不必要的字符串、parseInt等。很酷,很高兴知道它工作了!而且不需要向任何人更新问题的答案或标注-真的,发布的答案就足够了。有时,更新的答案甚至变得可用,并且更适合。也就是说,如果将来有人修改它以使其他用户更清楚地阅读,不要感到惊讶。
const top = this.chatScrollTop + this.boxScrollTop;
const marginLeft = this.chatScrollLeft + this.boxScrollLeft;

moveable1.style.top = top.toFixed(0) + "px";
moveable1.style.marginLeft = marginLeft.toFixed(0) + "px";