最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get style from click event target? - Stack Overflow

programmeradmin3浏览0评论

In angular material table, there is 24px padding-left on first cell:

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

How can i get it? ev.target.style.paddingLeft is empty.

stackblitz

In angular material table, there is 24px padding-left on first cell:

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

How can i get it? ev.target.style.paddingLeft is empty.

stackblitz

Share Improve this question edited Apr 7, 2019 at 1:23 yantrab asked Apr 5, 2019 at 10:16 yantrabyantrab 2,6904 gold badges35 silver badges59 bronze badges 6
  • I dont see any padding-left property in your CSS – Kunal Mukherjee Commented Apr 5, 2019 at 10:20
  • it is angular ponent, check the element in dev-tool – yantrab Commented Apr 5, 2019 at 10:22
  • You can use offsetWidth. From the link: Typically, offsetWidth is a measurement in pixels of the element's CSS width, including any borders, padding, and vertical scrollbars (if rendered) – Someone Commented Apr 5, 2019 at 10:27
  • it is give me 78, since when i click in the end i get event x grater the 78. – yantrab Commented Apr 5, 2019 at 10:37
  • The element itself does not have the padding-left: 24px; defined. It is getting the value from the classes that get applied to it. If properties are applied to the element, you could use ev.srcElement.style to get the values. The way suggested by @Mike would be the best approach in this case. – Sachin Gupta Commented Apr 5, 2019 at 10:42
 |  Show 1 more ment

2 Answers 2

Reset to default 4

The window.getComputedStyle() method is used to retrieve the current, actual, properties of an element. window.getComputedStyle(myElement).paddingLeft will give you the actual left padding of your element (with 'px' attached at the end). In order to pute the element's width + left padding, use the following:

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

If the width is fixed and never changes , just use myElement.width instead of getComputerStyle();

You can achieve what you want by passing the DOM element as a template parameter:

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

评论列表(0)

  1. 暂无评论