有没有一种简洁的方法可以选择所有 HTML 表单输入元素而无需重复规则选择器? 在我看来,



HTML有一个设计问题,表单输入元素不一致地type<input />(checkboxtext等)或它们自己的元素类型(selecttextarea等)。我知道这是基于元素对子元素的需求(<select><textarea>有子元素,但<input />没有),但不同类型的<input />会导致截然不同的渲染 - 例如,checkboxradio通常呈现为一个小的可点击的方形共享输入,而textpassword是矩形的,没有规定的宽度。

这意味着,如果要设置输入样式,则需要多个规则。

给定此 HTML:

<div class="field">
<label>
<input type="checkbox" /> Option 1
</label>
<label>
<input type="checkbox" /> Option 2
</label>
</div>
<div class="field">
A question?
<label>
<input type="radio" /> Option 1
</label>
<label>
<input type="radio" /> Option 2
</label>
</div>
<div class="field">
<label>
Your name
<input type="text" />
</label>
</div>
<div class="field">
<label>
An essay
<textarea></textarea>
</label>
</div>

如果只想设置文本输入的样式,则可能认为只需要:

input,
textarea {
border: 1px inset green;
}

但是,这也将(不恰当地)设置radiocheckbox输入的样式,因此您需要设置input样式,然后为input[type=radio]input[type=checkbox]添加新规则,以重新设置样式以匹配您的设计或重置其样式 - 或更改规则以匹配input[type=text]

但两者都不是完美的,因为输入规则仍然没有为其他类型的input指定样式:要么是那些以文本框为模型的样式(例如passwordemail)或那些不是(colorimagefile等)。除了所有其他表单元素(如selecttextareabutton等)之外,您还需要为您认为可能需要的每种类型添加一个规则,然后您需要为每种情况重复这些选择器,样式在新上下文中需要不同:

input[type=text],
input[type=password],
input[type=search],
input[type=tel],
input[type=url],
input[type=email],
textarea {
border: 1px inset green;
}
input[type=radio],
input[type=checkbox] {
border: none;
}
.someWrapper input[type=text],
.someWrapper input[type=password],
.someWrapper input[type=search],
.someWrapper input[type=tel],
.someWrapper input[type=url],
.someWrapper input[type=email],
.someWrapper textarea {
border: 1px inset green;
}
.someWrapper input[type=radio],
.someWrapper input[type=checkbox] {
border: none;
}
/* etc */

但是我觉得很多输入可以归入"输入类",比如"文本输入"类:textpasswordtextareaemailsearch等——"盒子输入"类:checkboxradio、"日期"类:datedatetimemonth等,等等。

因此,与其手动将这些类作为class值添加到我在 HTML 中的输入中,是否有任何浏览器固有的方式,例如通过 CSS 伪类,例如input:textbox还是input:boxinput?如果是这样,这将大大简化表单的CSS选择器,并减少缺少选择器的CSS错误。

幸运的是,CSS 中有一些东西几乎可以做到你想要的。:read-write伪选择器 (https://developer.mozilla.org/en-US/docs/Web/CSS/:read-write) 选择可由用户编辑的元素。

请考虑以下事项:

<input type="radio" selected /><br/>
<input type="checkbox" selected><br>
<input type="button" value="Click me"><br>
<input type="submit" value="Submit me"><br>
<input type="text"><br>
<input type="password"><br>
<input type="email"><br>
<input type="date"><br>
<textarea></textarea><br>

底部的 5 个元素(不包括brs)将被选中并用以下一行 CSS 突出显示:

*:read-write {border:1px solid #f3f;}

浏览器支持对于基本表单字段相当不错。

注意:我说几乎在第一行。这将选择日期字段。

您应该能够只使用input[type]但是,这在应用于selecttextarea字段时不一定对您有所帮助。但是无论如何,您都必须添加这些选择器。

input[type],
textarea {
border: 1px inset green;
}
input[type=radio],
input[type=checkbox] {
border: none;
}
input[type],
textarea {
border: 1px inset green;
}
input[type=radio],
input[type=checkbox] {
border: none;
}
<input type="text"/><br/>
<input type="button" value="click"/><br/>
<input type="checkbox"/><br/>
<input type="radio"/><br/>
<input type="color"/><br/>
<textarea></textarea>

相关内容

最新更新