.
3ss.cn

jquery怎么样添加css样式

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

在运用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>

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>
赞(0)
未经允许不得转载:互联学术 » jquery怎么样添加css样式

评论 抢沙发