【问题标题】:Inline style with data attribute using JavaScript no jQuery, changing color带有数据属性的内联样式使用 JavaScript 没有 jQuery,改变颜色
【发布时间】:2022-11-21 04:58:11
【问题描述】:

我有这个 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);
}

记者:

//Convert to inline styling

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

【问题讨论】:

  • “转换为内联样式”是什么意思?你想根据数据播放器属性更改背景颜色吗?
  • 所以两个玩家都会输入他们想要的颜色,所以通过在 js 中使用内联样式,我想将硬币的默认颜色更改为玩家提供的颜色。换句话说,我想在我的 js 文件中设置该属性的样式。
  • 我试过这个:piece.style.backgroundColor = "green",但我不知道如何定位数据属性 data-player = "1"。

标签: javascript css


【解决方案1】:

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

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

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

element.dataset.player = "2"

查看 dataset 的文档。

或者:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 2012-07-05
    相关资源
    最近更新 更多