jQuery 将 CSS 类添加到所有 <input type'text'> 元素?Javascript / CSS?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2836030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding Css class to all <input type'text'> elements? Javascript / Css?
提问by 4imble
I want to apply a CSS class to every textbox in my site:
我想将 CSS 类应用于我网站中的每个文本框:
<div class="editor-label">
<label for="FoodType">FoodType</label>
</div>
<div class="editor-field">
<input id="HelpText" name="FoodType" type="text" value="" />
</div>
<p>
<input type="submit" value="Create" />
</p>
And I thought, Hey! Easy. I'll add a jquery function to find them all in the masterpage.
我想,嘿!简单。我将添加一个 jquery 函数来在母版页中找到它们。
<script type="text/javascript">
$(document).ready(function(){
$('input').addClass('textbox');
}
</script>
Unfortunately this will also select the submit button. How can i only select input elements that have a text type attribute?
不幸的是,这也会选择提交按钮。如何只选择具有文本类型属性的输入元素?
Alternativly is this possible using entirely CSS?
或者,这是否可以完全使用 CSS?
If both these methods are not possible, i guess i will just have to manually add the class to every textbox i make?
如果这两种方法都不可能,我想我只需要手动将类添加到我制作的每个文本框?
回答by eglasius
AFAIK it's:
AFAIK它是:
$('input[type=text]').addClass('textbox');
And you can do similar in the CSS file, but that requires higher version of CSS / depending how broad you want to be with older browsers.
并且您可以在 CSS 文件中执行类似操作,但这需要更高版本的 CSS / 取决于您希望使用旧浏览器的范围。
See attribute selectors in here. Note that:
请参阅此处的属性选择器。注意:
"Browser support: The only browser that doesn't support CSS3 attribute selectors is IE6. Both IE7 and IE8, Opera and Webkit- and Gecko-based browsers do. So using them in your style sheet is definitely safe."
“浏览器支持:唯一不支持 CSS3 属性选择器的浏览器是 IE6。IE7 和 IE8、Opera 和基于 Webkit 和 Gecko 的浏览器都支持。因此在样式表中使用它们绝对是安全的。”
回答by Sahil Jain
<!DOCTYPE html>
<html>
<head>
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$(".post_class").css({padding:"10px",background:"#333",color:"#fff"});
$("#post_button").css({padding:"10px",background:"#333", textAlign:"center",color:"#fff",cursor:"pointer"})
$("#post_button").click(function(){
var input = $("input[name='checkListItem']").val();
$(".post_class").append('<div class="item">' + input + '</div>');
});
});
</script>
</head>
<body>
<form name="checkListForm">
<input type="text" name="checkListItem"/>
</form>
<div id="post_button">Post</div>
<br/>
<div class="post_class"></div>
</body>
</html>