因此,由于某些不利的原因,我无法直接访问css或HTML,因此在某些复选框上设置几种样式时遇到了一些麻烦。但是,我可以使用Pure Javascript影响我的项目。
我建立了一个基本功能,旨在用两种样式来设置页面上所有复选框的样式。float: left; & marginRight: 1em。我包括了一个小片段,显示了我的劳动成果。
function styleEl() {
// get all elements...
var bxSyl = document.querySelectorAll('input[type=checkbox]');
// console.log(bxSyl);
[].forEach.call(bxSyl, function(bs) {
// style elements...
bs.style.cssFloat = "left";
bs.style.marginRight = "1em";
});
};
// call it...
styleEl();Run Code Online (Sandbox Code Playgroud)
.editoropt {
font-family: Calibri, sans-serif;
width: 300px;
background: #0f0;
padding: .5em;
}Run Code Online (Sandbox Code Playgroud)
<div class="seq-box-form-field editoropt ">
<label for="opt1"><span style="padding-right: 10px; vertical-align: 1px;">Ground Floor </span>
<input type="checkbox" name="checkboxopt" id="checkboxopt" value="true" checked="true" />
<input type="hidden" name="opt1" id="opt1" value="true" />
</label>
</div>
<div class="seq-box-form-field editoropt ">
<label for="opt1"><span style="padding-right: 10px; vertical-align: 1px;">First Floor </span>
<input type="checkbox" name="checkboxopt" id="checkboxopt" value="true" checked="true" />
<input type="hidden" name="opt1" id="opt1" value="true" />
</label>
</div>
<div class="seq-box-form-field editoropt ">
<label for="opt1"><span style="padding-right: 10px; vertical-align: 1px;">Second Floor </span>
<input type="checkbox" name="checkboxopt" id="checkboxopt" value="true" checked="true" />
<input type="hidden" name="opt1" id="opt1" value="true" />
</label>
</div>
<div class="seq-box-form-field editoropt ">
<label for="opt1"><span style="padding-right: 10px; vertical-align: 1px;">Third Floor</span>
<input type="checkbox" name="checkboxopt" id="checkboxopt" value="true" checked="true" />
<input type="hidden" name="opt1" id="opt1" value="true" />
</label>
</div>Run Code Online (Sandbox Code Playgroud)
经过测试,这些js设置样式将被忽略。因此,问题的根源。
我知道设置时
!important需要像这样使用setProperty;document.body.style.setProperty ("color", "green", "important");
但是,如果我在使用JS的示例中一次将其添加到所有样式中怎么办?这样做是个好主意吗?如果不是为什么?
如果可以使用这种方法,我该怎么做?
可能的答案
// inject style
function ctSe() {
var css = "input[type='checkbox'] { float:left; margin-right: 1em !important;}",
head = document.head || document.getElementsByTagName('head')[0],
style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
head.appendChild(style);
console.log(head)
console.log(style)
console.log(css)
};
ctSe();
Run Code Online (Sandbox Code Playgroud)
小智 0
应避免使用!important,并且在所有情况下都是最后的手段。一般来说,CSS 中的继承几乎适用于所有情况。
但是,偶尔您需要将属性强制为继承的样式以外的样式。
通常,仅覆盖那些行为不当的属性。
恕我直言,把!important所有东西都穿上是不明智的。