如何从点击事件目标中获取样式?

时间:2019-04-05 10:16:56

标签: javascript html angular angular-material

在棱角材质表中,第一个单元格的左边距为24px:

td.mat-cell:first-of-type, td.mat-footer-cell:first-of-type, th.mat-header-cell:first-of-type {
    padding-left: 24px;
}

我如何得到它? ev.target.style.paddingLeft为空。

stackblitz

2 个答案:

答案 0 :(得分:3)

您可以通过将DOM元素作为模板参数来实现所需的目标:

<th mat-header-cell *matHeaderCellDef #parameter (click)="cellClick($event, parameter)" > No. </th>
cellClick(ev: MouseEvent, element: HTMLElement) {
 console.log(element.offsetWidth);
}

答案 1 :(得分:1)

window.getComputedStyle()方法用于检索元素的当前实际属性。 window.getComputedStyle(myElement).paddingLeft将为您提供元素的实际左侧填充(末尾附加“ px”)。 为了计算元素的宽度+左填充,请使用以下命令:

+window.getComputedStyle(myElement).paddingLeft.slice(0, -2) + 
+window.getComputedStyle(myElement).width.slice(0, -2);

如果宽度是固定的,并且从不改变,则只需使用myElement.width而不是getComputerStyle();