【问题标题】:How to get style from click event target?如何从点击事件目标中获取样式?
【发布时间】:2019-04-12 13:13:34
【问题描述】:

在角度材质表中,第一个单元格有 24px 的 padding-left:

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

【问题讨论】:

  • 我在你的 CSS 中没有看到任何 padding-left 属性
  • 它是角度组件,检查开发工具中的元素
  • 您可以使用offsetWidth。来自链接:通常,offsetWidth 是以像素为单位的元素 CSS 宽度的度量,包括任何边框、填充和垂直滚动条(如果呈现)
  • 它是给我 78,因为当我点击最后我得到事件 x grater 78。
  • 元素本身没有定义padding-left: 24px;。它从应用到它的类中获取价值。如果属性应用于元素,您可以使用ev.srcElement.style 来获取值。在这种情况下,@Mike 建议的方法将是最好的方法。

标签: javascript html angular angular-material


【解决方案1】:

您可以通过将 DOM 元素作为模板参数传递来实现您想要的:

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

【讨论】:

  • 它给了我同样的结果 - 78px。
  • ev.target 是元素。
  • 我正在查看您的 stackblitz,它给出的结果为 102px(窗口较大)
【解决方案2】:

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

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

如果宽度是固定不变的,就用myElement.width代替getComputerStyle()

【讨论】:

    猜你喜欢
    • 2017-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-30
    • 1970-01-01
    相关资源
    最近更新 更多