Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

A client has changed their CSP to ban inline styles on their server. As far as I can tell, this means that we can no longer use JS to dynamically position/animate/style HTML elements e.g. we can't detect the position of a DOM element and position another element next to it via JS.

Is this correct? Is there a workaround for us to dynamically animate DOM elements with this CSP restriction in place?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
319 views
Welcome To Ask or Share your Answers For Others

1 Answer

The proper workaround for this issue is to use the CSS Object Model (CSSOM).

Given the following ways of setting the style:

  1. <p style="left: 343px">...</p> // fails due to CSP
  2. document.getElementById(id).setAttribute('style', 'left: 343px'); // fails due to CSP
  3. document.getElementById(id).style.left = '343px';

Only the last one will successfully comply with a CSP directive of style-src: self (because it's using the CSSOM).

That's why using jQuery's .css() function works:

When using .css() as a setter, jQuery modifies the element's style property. For example, $( "#mydiv" ).css( "color", "green" ) is equivalent to document.getElementById( "mydiv" ).style.color = "green".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...