本文摘自PHP中文网,作者藏色散人,侵删。
js添加css样式的方法:1、通过调用元素的css方法来添加样式;2、通过addClass来添加css样式,语句如“$("#txtName").addClass("aa");”。
本文操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。
js如何添加css样式?
添加css样式方法汇总
由于jquery支持css3,所有能很好的兼容很多浏览器,
所以通过jquery来使用css样式比较好。
为定义好的css样式可以调用元素的css方法添加样式
1 2 3 | $( "span" ).css( "css属性名" , "属性值" )
如:
$( "span" ).css( "color" , "red" ) 将标签为span的字体都设为红色的
|
如果是定义好的css样式,可以通过addClass来添加,比如
1 2 3 4 5 6 7 8 | <style type= "text/css" >
.aa {border:1px solid red;}
</style>
<input id= "txtName" type= "text" value= "请输入你的姓名" />
<script>
$( "#txtName" ).addClass( "aa" );
</script>
|
下面列举下对css样式操作的方法:
1 2 3 4 5 6 7 8 | 1、.css( "样式" ):获得样式值,比如$( "input" ).css( "color" ) 获得input中字体的颜色
2、.css( "样式" , "value" ):为样式赋值,如$( "input" ).css( "color" , "red" );
3、.addClass( "样式类1,样式类2,样式类3" ):可以添加多个定义好的样式类
4、.hasClass( "样式类类" ):判断是否存在该样式
5、.toggleClass( "样式类" ):如果存在(不存在)就切换(删除)样式
6、.toggleClass( "样式类" ,swith):如果swith为false,则删除样式,如果swith为true,则切换成该类
7、.removeClass( "样式类" ):移除样式类
8、.css({样式名: "value" ,样式名: "value" ,样式名: "value" }):可以多次添加样式
|
判断display隐藏显示
1 2 3 4 5 6 7 8 9 | function isHide(obj) {
var ret = obj.style.display === "none" ||
obj.style.display === "" ||
(obj.currentStyle && obj.currentStyle === "none" ) ||
(window.getComputedStyle && window.getComputedStyle(obj, null).display === "none" )
return ret;
}
|
推荐:《javascript高级教程》
以上就是js如何添加css样式的详细内容,更多文章请关注木庄网络博客!
相关阅读 >>
实例汇总js call()及apply()的方法使用
关于js中的this指向问题的介绍
js生成1到100的随机数
javascript 中cookie读、写与删除操作(图文教程)
js中substring、slice与substr的区别有哪些?
为什么css放上面js放下面
js函数的回调
秒懂js的垃圾回收机制
js如何实现递归函数
js的prototype是什么
更多相关阅读请进入《js》频道 >>
人民邮电出版社
本书对 Vue.js 3 技术细节的分析非常可靠,对于需要深入理解 Vue.js 3 的用户会有很大的帮助。——尤雨溪,Vue.js作者
转载请注明出处:木庄网络博客 » js如何添加css样式