如何获取点击元素的样式 - “currentTarget”

鸭子

currentTarget当我添加stylehtml 元素时有效。如何在style不添加stylehtml 元素的情况下访问被点击元素文件

const all = document.querySelectorAll(".all");

all.forEach((button) => {
  button.addEventListener("click", (e) => {
    let bgColor = e.currentTarget.style.backgroundColor;
    console.log(bgColor);
  });
});
div {
  color: white;
  height: 2em;
  width: 15em;
  margin: 2em;
  padding: 2em;
  
  background-color: royalblue;
}

span {
  color: white;
  height: 2em;
  width: 15em;
  margin: 2em;
  padding: 2em;
  
  background-color: red;
}
<div class="all">I'm a thin, big and insulated also soft, prickly box.</div>

<span style="background-color: black;" class="all">I am useless</span>

https://jsfiddle.net/bcz0t6gx/

光谱

使用window.getComputedStyle()得到的CSSStyleDeclaration的元素,并getPropertyValue()获得CSS属性的值:

const all = document.querySelectorAll(".all");

all.forEach((button) => {
  button.addEventListener("click", (e) => {
    let bgColor = window.getComputedStyle(e.currentTarget).getPropertyValue("background-color");
    console.log(bgColor);
  });
});
.all {
  color: white;
  height: 2em;
  width: 15em;
  margin: 2em;
  padding: 2em;
  
  background-color: royalblue;
}

span {
  color: white;
  height: 2em;
  width: 15em;
  margin: 2em;
  padding: 2em;
  
  background-color: red;
}
<div class="all">I'm a thin, big and insulated also soft, prickly box.</div>

<span style="background-color: black;" class="all">I am useless</span>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

获取currentTarget的子代的innerHTML

我的event.currentTarget如何自动更改?

反应如何从event.currentTarget获取道具

使用 karma 在 Angular 中获取 e.currentTarget 的测试事件

使用jQuery .click()模拟元素点击后,未定义event.currentTarget

如何比較 e.currentTarget 和 e.Target?

我使用了e.currentTarget.dataset.id来获取被点击的li的inex值,但是却给了我undefined。

使用event.currentTarget.className将类添加到元素

如何从React Native可触摸事件currentTarget中读取道具?

如何告诉打字稿输入event.currentTarget.value我们一个数字?

event.currentTarget的实际用法?

正确使用clickTarget jQuery的currentTarget

访问currentTarget的公共属性

setTimeout之后事件currentTarget发生更改

如何按类获取点击元素的索引?

如何获取jstree行元素的点击事件?

jQuery如何获取点击元素的索引?

如何获取JSON格式的元素样式?

如何获取元素的样式值-jQuery

如何获取当前元素的计算样式

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

ReactJS,event.currentTarget与Vanilla Javascript具有不同的行为

e.target和e.currentTarget之间的区别

为什么e.currentTarget随着jQuery的事件委托而改变?

事件委派,Event.target与Event.currentTarget

event.currentTarget.files 在 React Typescript 上不起作用

反应事件 currentTarget textContent 显示所有值

我怎么能访问和使用event.currentTarget但当我打印事件时currentTarget为null?

获取子元素被点击