简体   繁体   English

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

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

I have this piece element, which represents a coin in my connect four game, however, I want to change the background color of the coin using inline styling in JS.我有这个 piece 元素,它代表我的 connect four 游戏中的硬币,但是,我想使用 JS 中的内联样式更改硬币的背景颜色。 Is it possible to convert the CSS format to inline js styling?是否可以将 CSS 格式转换为内联 js 样式? I have tried using getAttribute but don't think I am using right.我试过使用 getAttribute 但我认为我使用的不正确。 Any suggestions would be helpful.任何的意见都将会有帮助。

style.css:样式.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);
}

JS:记者:

//Convert to inline styling //转换为内联样式

I have tried using the getattribute but doesn't change anything in my webpage.我试过使用 getattribute 但没有改变我网页中的任何内容。

Assuming you have a HTML markup like:假设您有一个 HTML 标记,例如:

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

Changing its data- attribute's value should do it.更改其data-属性的值应该可以做到。 So assuming you targeted an element with a data-player="1" :因此,假设您使用data-player="1"定位了一个元素:

element.dataset.player = "2"

Look the documentation for dataset .查看dataset的文档。

Or:或者:

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

just get the element by attribute selector and set its style attribute with background-color只需通过属性选择器获取元素并将其样式属性设置为背景颜色

  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