动态 CSS 值

问题描述

我们的应用程序中使用了很多内联样式。 我正在努力摆脱它们,因为它们容易受到 XSS 攻击。 虽然我已经能够用 CSS 类替换其中的大部分,但很少有像下面这样根据 var= backgroundColor 的值动态设置样式值

                <c:choose>
                    <c:when test="${order.isdisabled()}">
                        <c:set var="backgroundColor" value="#f0f0f0"/>
                    </c:when>
                    <c:when test="${empty order.isConfirmed}">
                        <c:set var="backgroundColor" value="transparent"/>
                    </c:when>
                    <c:otherwise>
                        <c:set var="backgroundColor">${record.statusBGColor}</c:set>
                    </c:otherwise>
                </c:choose>

                <reg class="reg">
                    <rect width="100%" height="100%" style="fill:${backgroundColor};"></rect>
                </reg>
            </div>

有没有办法创建一个 css 类,它动态地接受一个值(${backgroundColor)或其他一些我可以删除内联样式的方式?

我们在我们的应用程序中使用 jquery

解决方法

如果您只是想删除 rect 的内联填充样式,您可以在 js 中这样做:

var element = document.getElementsByTagName("rect");
for(var i = 0; i < element.length; i++)
{
   element[i].style.removeProperty('fill');
  }

或者,如果您想使用 jquery 删除所有内联样式,这是一个有用的命令:

$('rect').removeAttr('style');

或者,如果您真的想取消所有内联样式的所有内容,则可以这样做:

$('*').removeAttr('style');