我可以使用对象属性值作为css属性值吗?

时间:2018-05-31 17:49:09

标签: javascript css dom

我有一个属性的对象,其值将反复变化。 与此同时,我需要css属性的值来镜像对象属性值。 下面是我的javascript函数,它将与其他东西一起执行...

const initStats = () => {
stats();



let uD = document.querySelector("#defense")
  let uSp= document.querySelector("#speed")
  let uSt = document.querySelector("#strength")
  let uHth = document.querySelector("#health")

  uD.textContent = "Defense: " + fighterUser.defense
  let width = fighterUser.defense
  const content = document.createElement('div');
  content.classList.add('content');
  content.style.width = fighterUser.defense
  uD.appendChild(content);


  uSp.textContent = "speed: " + fighterUser.speed
  uSt.textContent = "Strength: " + fighterUser.strength
  uHth.textContent = "health: " + fighterUser.health


  let cD = document.querySelector("#defense-cpu")
  let cSp= document.querySelector("#speed-cpu")
  let cSt = document.querySelector("#strength-cpu")
  let cHth = document.querySelector("#health-cpu")

  cD.textContent = "Defense: " + fighterCpu.defense
  cSp.textContent = "Speed: " + fighterCpu.speed
  cSt.textContent = "Strength: " + fighterCpu.strength
  cHth.textContent = "health: " + fighterCpu.health
}

这是我需要帮助的部分,我试图做这样的事情,但我知道css不会采取" fighterUser.defense"作为一个价值......

uD.textContent = "Defense: " + fighterUser.defense
  let width = fighterUser.defense
  const content = document.createElement('div');
  content.classList.add('content');
  content.style.width = fighterUser.defense
  uD.appendChild(content);

谢谢大家!

1 个答案:

答案 0 :(得分:0)

您可以添加' px'或者是'%'相对于父节点并指示可以测量该值:

content.style.width = fighterUser.defense + 'px'