开发者

style.setProperty does not render

开发者 https://www.devze.com 2023-04-12 04:12 出处:网络
It seems like using this function would be more portable or reliable, because the alternative is to set an attribute:

It seems like using this function would be more portable or reliable, because the alternative is to set an attribute:

element.style.setProperty(styleproperty, valuestring);
element.setAttribute('style',styleproperty+': '+valuestring+';');

The second method would also seem slightly more inefficient though that's hardly a concern.

But at least on Chrome, the style does not update on the page unless I use the setAttribute method.

The reas开发者_C百科on why this is a bit of an issue, is that I have potentially many different separate style properties I want to modify independently of the others. I have to do a whole lot of string parsing and processing if I can't make use of setProperty, removeProperty, etc. I have to pull out the style string, search it, modify it, and set it back in via setAttribute. Should work, but I don't like it.

Is there a reason for this? Is this a bug? My guess is that setAttribute triggers something for the browser to perform a re-render. What is a suitable way to force this update that is generally browser-friendly?


Setting the style attribute directly has consequences that may be undesirable: it will wipe out all existing styles set in the element's style attribute, and setAttribute is broken in older IE (and compatibility modes in later IE). Much safer is to use the element's style property directly to set only the style property you need:

element.style[styleproperty] = valuestring;

This will update the page immediately in all major browsers.

One caveat: CSS style properties (generally using dashes, such as in background-color) do not map precisely to properties of the DOM element's style object (generally camel case, such as in backgroundColor). There are also exceptions to this rule.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号