繁体   English   中英

使用 JavaScript no jQuery 的数据属性的内联样式,改变颜色

[英]Inline style with data attribute using JavaScript no jQuery, changing color

我有这个 piece 元素,它代表我的 connect four 游戏中的硬币,但是,我想使用 JS 中的内联样式更改硬币的背景颜色。 是否可以将 CSS 格式转换为内联 js 样式? 我试过使用 getAttribute 但我认为我使用的不正确。 任何的意见都将会有帮助。

样式.css:

.piece{
  border-radius: 50%;
  background-color: red;
  flex-grow: 1;
  margin: 5%;
}

.piece[data-placed = "false"]{
  transform: translateY(-10vmin);
}
.piece[data-player = "1"]{                 //This is the element I want to inline style in my js file
  background-color: rgb(25, 0, 255);
}
.piece[data-player = "2"]{                  //This is the element I want to inline style in my js file
  background-color: rgb(255, 0, 0);
}

记者:

//转换为内联样式

我试过使用 getattribute 但没有改变我网页中的任何内容。

假设您有一个 HTML 标记,例如:

<div class="piece" data-player="1"></div>

更改其data-属性的值应该可以做到。 因此,假设您使用data-player="1"定位了一个元素:

element.dataset.player = "2"

查看dataset的文档。

或者:

element.setAttribute("data-player", "2")

只需通过属性选择器获取元素并将其样式属性设置为背景颜色

  document
      .querySelector('.piece[data-player="1"]')
      .setAttribute('style', 'background-color: yellow');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM