jquery添加css样式的方法:1、使用addClass()方法添加css样式,语法如“$(selector).addClass(class)”;2、使用css()方法设置css样式,语法如“css("propertyname")”。

本文操作环境:windows7系统、jquery1.2.6版、Dell G3电脑。
在运用jquery的时候我们经常需要动态的给一些dom元素添加CSS样式,下面我们来看一下Jquery如何动态的添加css样式。
jquery添加css样式的方法:
使用addClass() 方法添加css样式。
立即学习“前端免费学习笔记(深入)”;
使用css() 方法设置css样式。
1、使用addClass() 方法添加css样式
addClass() 方法向被选元素添加一个或多个类。该方法不会移除已存在的 class 属性,仅仅添加一个或多个 class 属性。
注:如需添加多个类,请使用空格分隔类名。
语法:
$(selector).addClass(class)
示例:
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$("p:first").addClass("intro");
});
});
</script>
<style type="text/css">
.intro
{
font-size:120%;
color:red;
}
</style>
</head>
<body>
<h1>This is a heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>向第一个 p 元素添加一个类</button>
</body>
</html>【推荐学习:jquery视频教程】
2、使用css() 方法设置css样式
css() 方法设置或返回被选元素的一个或多个样式属性。
如需返回指定的 CSS 属性的值,请使用如下语法:
css("propertyname");如需设置指定的 CSS 属性,请使用如下语法:
css("propertyname","value");示例:
<!DOCTYPE html>
<html>
<head>
<script src="/jquery/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").css("background-color","yellow");
});
});
</script>
</head>
<body>
<h2>这是标题</h2>
<p style="background-color:#ff0000">这是一个段落。</p>
<p style="background-color:#00ff00">这是一个段落。</p>
<p style="background-color:#0000ff">这是一个段落。</p>
<p>这是一个段落。</p>
<button>设置 p 元素的背景色</button>
</body>
</html>以上就是jquery怎么添加css样式的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号