You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用原生JS实现带data属性元素的内联背景色修改

四子棋棋子:将CSS data-player关联样式转为JS内联样式

需求

开发四子棋时,需用原生JavaScript替代CSS中基于data-player属性的棋子背景色样式,改为内联样式实现。尝试使用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"]{
  background-color: rgb(25, 0, 255);
}
.piece[data-player = "2"]{
  background-color: rgb(255, 0, 0);
}

解决方案

getAttribute仅用于读取属性值,无法直接设置样式。正确做法是获取所有.piece元素,根据其data-player属性值设置对应的内联背景色:

实现代码

// 获取所有棋子元素
const pieces = document.querySelectorAll('.piece');

// 遍历设置内联样式
pieces.forEach(piece => {
  const player = piece.getAttribute('data-player');
  switch(player) {
    case '1':
      piece.style.backgroundColor = 'rgb(25, 0, 255)';
      break;
    case '2':
      piece.style.backgroundColor = 'rgb(255, 0, 0)';
      break;
    // 可添加默认情况,对应原CSS的默认红色
    default:
      piece.style.backgroundColor = 'red';
  }
});

额外提示

  • 若棋子是动态生成的(如落子后新增),需在元素创建完成后调用上述代码,或通过DOM监听事件触发样式设置。
  • 原CSS中.piece[data-placed="false"]的transform样式可保留,若需转为内联样式,同理判断data-placed属性后设置piece.style.transform = 'translateY(-10vmin)'即可。

内容的提问来源于stack exchange,提问作者John Fisher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 04:50:45