简体   繁体   中英

setting a style using a string value javascript

Hi i want to know if there is a way of setting a style of on object through javascript using a string, i don't know how to explain it very well hopefully my code will

function updateElementFromValue(inputval, valueOfStyle)
{
  selectedActiveElement.style.valueOfStyle = inputval.value + "px";
}

so i have this function and when i call it, inputval will be an input field and valueOfStyle will be passed as top or left or width etc so it effectively becomes, ignore selectedActiveElement as it is a global object.

  selectedActiveElement.style.top = 200 + "px";

i figure im not calling it right but i think their is a way of doing this.

Thanks for you help

You can use the setProperty function
element.style.setProperty(valueOfStyle, inputval.value + "px")

Also you're able to do sth. like this:
element.style[valueOfStyle] = inputval.value + "px"
but I would not recommend it since not every browser supports that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM