【问题标题】:Resetting all CSS styles for a widget重置小部件的所有 CSS 样式
【发布时间】:2013-08-15 04:25:15
【问题描述】:

我正在创建一个使用许多自定义样式的 Javascript 小部件。当用户将小部件放在他的页面上时,用户的页面总是会影响小部件的样式。有没有办法防止这种情况发生?

例如,如果我的小部件中有一个输入框:

<input id="#special-input" />

而且用户的样式会覆盖输入:

input { width: 500px; }

然后,用户的页面会覆盖输入框的宽度。用户可以通过多种方式更改小部件的样式,我无法解释所有这些方式。例如,对于输入,我必须考虑边框、阴影、宽度、高度等以及用户可以设置页面样式并影响我的小部件的任何其他方式。

【问题讨论】:

  • 方法广泛。请举例说明正在发生的事情。
  • 声明内联样式:&lt;div style="width:100px"&gt;。然后最终用户必须显式使用 !important 来覆盖它们。
  • 另一个提示:使用其他网页不太可能使用的特定 id 和类。
  • 已编辑。即使我声明了内联样式,也有许多 CSS 属性会间接影响我的小部件的 CSS。如果用户设置了一个最终影响我的小部件的 input:hover CSS 属性怎么办?有很多事情要担心。
  • 这可能有点矫枉过正,但这是我唯一能想到的。您可以在小部件的特定元素上使用window.getComputedStyle,遍历结果,然后清除它找到的所有样式。完成后,应用您的样式,您应该一切顺利。只需确保针对您的特定元素,这样您就不会最终将整个页面擦干净...

标签: javascript html css


【解决方案1】:

要背负我上面的评论,您可以执行以下操作。 (完全未经测试,很快就拼凑起来了)这使用了 Jquery,但我相信如果你使用另一个库或纯 JS,你可以弄清楚如何修改它。

var allStyles = ["azimuth","background","backgroundAttachment","backgroundColor","backgroundImage","backgroundPosition","backgroundRepeat","border","borderBottom","borderBottomColor","borderBottomStyle","borderBottomWidth","borderCollapse","borderColor","borderLeft","borderLeftColor","borderLeftStyle","borderLeftWidth","borderRight","borderRightColor","borderRightStyle","borderRightWidth","borderSpacing","borderStyle","borderTop","borderTopColor","borderTopStyle","borderTopWidth","borderWidth","bottom","captionSide","clear","clip","color","content","counterIncrement","counterReset","cssFloat","cue","cueAfter","cueBefore","cursor","direction","display","elevation","emptyCells","font","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontStyle","fontVariant","fontWeight","height","left","letterSpacing","lineHeight","listStyle","listStyleImage","listStylePosition","listStyleType","margin","marginBottom","marginLeft","marginRight","marginTop","markerOffset","marks","maxHeight","maxWidth","minHeight","minWidth","orphans","outline","outlineColor","outlineStyle","outlineWidth","overflow","padding","paddingBottom","paddingLeft","paddingRight","paddingTop","page","pageBreakAfter","pageBreakBefore","pageBreakInside","pause","pauseAfter","pauseBefore","pitch","pitchRange","playDuring","position","quotes","richness","right","size","speak","speakHeader","speakNumeral","speakPunctuation","speechRate","stress","tableLayout","textAlign","textDecoration","textIndent","textShadow","textTransform","top","unicodeBidi","verticalAlign","visibility","voiceFamily","volume","whiteSpace","widows","width","wordSpacing","zIndex"];

    $.each(allStyles, function(key, value){
        if ($this.css(value) !== undefined){
            $this.css(key, "")
        }
    });

注意我上面的帖子是根据另一个主题的这个答案修改的。只是想感谢@Matrym...getComputedStyle (or) $.css(map) <-- to get every style declaration

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多