Home > Blockchain >  CSS/JS : How to Retrieve a numerical value from a CSS property in JS and modify it?
CSS/JS : How to Retrieve a numerical value from a CSS property in JS and modify it?

Time:11-25

I've tried looking around but was not able to find a clear/easy answer.

Let's say I want to retrieve some value (size) in px for a CSS style sheet like this :

#block{
  width: 150px;
  height: 150px;
  background-color: #f00;
  position: absolute;
  left: 0;
  top: 0;
}

I've tried

let block = document.getElementById("block");
const square = window.getComputedStyle(block)
const width = square.getPropertyValue('width');
block.style.width = size.value * width;

But it returns a string. I'd like to modify the value in px dynamically with JS. Is there a better way or should I create a substring, then convert it to a number?

EDIT : I've also tried

let width = block.offsetWidth;

But the result on my page is not at all functional.

CodePudding user response:

Try This :

   let element = document.getElementById('block');
   let positionInfo = element.getBoundingClientRect();
   let height = positionInfo.height;
   let width = positionInfo.width;

CodePudding user response:

I don't think there is a built in function to get a unitless number from a length.

Meanwhile, calc() can convert a number to a length, so it's possible to do it the other way around:

var r = document.querySelector(':root');
r.style.setProperty('--size-value', 50);
:root {
  --size-value: 16;
  --size: calc(var(--size-value) * 1px);
}

p {
  font-size: var(--size);
}
<p>Hello</p>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related