尝试在打字稿中为CSS分配值不起作用

问题描述 投票:0回答:1

我有一个脚本,它采用HTMLElement和一个拒绝在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

思绪,有人吗?

更新:

Zeh提出了解决方案:

我修改了一下......

  let top = +this.chatScrollTop + +this.boxScrollTop;

  const marginLeft = this.chatScrollLeft + this.boxScrollLeft;

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

  console.log("top: " + moveable1.style.top);
  console.log("marginLeft: " + moveable1.style.marginLeft);

谢谢你!

css3 typescript
1个回答
1
投票

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

此外,在设置样式时需要单位(“px”,“pt”等),否则它也不会设置,即使它是string。因此,当您尝试将它们从数字转换为字符串时,您将获得另一个空字符串

// 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";
© www.soinside.com 2019 - 2024. All rights reserved.