jQuery CSS 操作 - css() 方法

实例

设置 <p> 元素的颜色:

$(".btn1").click(function(){
  $("p").css("color","red");
});

定义和用法

css() 方法返回或设置匹配的元素的一个或多个样式属性。

返回 CSS 属性值

返回第一个匹配元素的 CSS 属性值。

注释:当用于返回一个值时,不支持简写的 CSS 属性(比如 "background" 和 "border")。

$(selector).css(name)
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    alert($("p").css("color"));
  });
});
</script>
</head>

<body>
<p style="color:red">This is a paragraph.</p>
<button type="button">返回段落的颜色</button>
</body>
</html>

设置 CSS 属性

设置所有匹配元素的指定 CSS 属性。

$(selector).css(name,value)
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $("p").css("color","red");
  });
});
</script>
</head>

<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button type="button">改变段落的颜色</button>
</body>
</html>

使用函数来设置 CSS 属性

设置所有匹配的元素中样式属性的值。

此函数返回要设置的属性值。接受两个参数,index 为元素在对象集合中的索引位置,value 是原先的属性值。

$(selector).css(name,function(index,value))
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $("p").css("color",function(){
    return "red";
    });
  });
});
</script>
</head>

<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button>设置所有 p 元素的 color 属性</button>
</body>
</html>
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("div").click(function() {
    $(this).css(
      "width", function(index, value) {return parseFloat(value) * 1.2;}
    );
  });
});
</script>
<style>
div {width:100px; height:50px; background-color:red;}
</style>
</head>

<body>
<div>请点击这里</div>
</body>
</html>

设置多个 CSS 属性/值对

$(selector).css({property:value, property:value, ...})

把“名/值对”对象设置为所有匹配元素的样式属性。

这是一种在所有匹配的元素上设置大量样式属性的最佳方式。

<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $("p").css({
      "color":"white",
      "background-color":"#98bf21",
      "font-family":"Arial",
      "font-size":"20px",
      "padding":"5px"
    });
  });
});
</script>
</head>

<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<button type="button">改变段落的样式</button>
</body>
</html>

 



转载于:https://www.cnblogs.com/jiqing9006/archive/2012/08/06/2625075.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值