如何用RGB值设置JS动态创建的Player元素背景色(无CSS)
问题描述
我正在使用w3spaces开发一款游戏,现有以下代码,希望将创建的player元素背景色设置为currentColor对应的RGB值(part1、part2、part3及currentColor是从Stack Overflow获取的RGB相关变量):
const createPlayer = (w,h) => { const player = document.createElement('div'); player.style.width = w + 'px'; player.style.height = h + 'px'; player.id = "player"; player.style.down = "150px"; return player; };
解决方案
根据你的需求,分两种场景实现背景色设置:
场景1:currentColor为合法RGB格式字符串(如rgb(255,0,0))
直接将currentColor赋值给player的背景色样式:
const createPlayer = (w,h) => { const player = document.createElement('div'); player.style.width = w + 'px'; player.style.height = h + 'px'; player.id = "player"; player.style.bottom = "150px"; // 修正无效的down属性为bottom player.style.backgroundColor = currentColor; // 设置背景色 return player; };
场景2:part1、part2、part3为RGB分量数值(如255、0、0)
用三个分量拼接成RGB字符串赋值:
const createPlayer = (w,h) => { const player = document.createElement('div'); player.style.width = w + 'px'; player.style.height = h + 'px'; player.id = "player"; player.style.bottom = "150px"; // 修正无效的down属性为bottom player.style.backgroundColor = `rgb(${part1}, ${part2}, ${part3})`; // 拼接RGB值 return player; };
注:原代码中的player.style.down是无效CSS属性,建议改为bottom来控制元素底部位置。
内容的提问来源于stack exchange,提问作者NoobGangNB1234
相关产品推荐
相关产品推荐

