通過js獲取dom元素上的style屬性殴瘦,我們可以動(dòng)態(tài)的給元素賦予樣式屬性。在jQuery中我們要?jiǎng)討B(tài)的修改style屬性我們只要使用.css()方法就可以實(shí)現(xiàn)了雹有。
.css()方法:獲取元素樣式屬性的計(jì)算值或者設(shè)置元素的css屬性
獲取:
1 .css(propertyName):獲取匹配元素集合中的第一個(gè)元素的樣式屬性的計(jì)算值
2 .css(propertyNames):傳遞一組數(shù)組,返回一個(gè)對(duì)象結(jié)果
設(shè)置:
1 .css(propertyName,value: 設(shè)置css
2 .css(propertyName,function) 可以傳入一個(gè)回調(diào)函數(shù)装盯,返回取得對(duì)相應(yīng)的值進(jìn)行處理
3 .css (properties):可以傳入一個(gè)對(duì)象,同時(shí)設(shè)置多個(gè)樣式
<body>
<h3>獲取css屬性</h3>
<div class="first">獲取顏色</div>
<p></p>
<div class="second">獲取文字尺寸</div>
<p></p>
<div class="third">獲取寬高尺寸</div>
<p></p>
<script type="text/javascript">
//background-color:blue; => rgb(0, 0, 255)
//顏色都會(huì)轉(zhuǎn)化成統(tǒng)一的rgb標(biāo)示
$('p:eq(0)').text( $('.first').css("background-color") )
</script>
<script type="text/javascript">
//字體大小都會(huì)轉(zhuǎn)化成統(tǒng)px大小 em=>px
$('p:eq(1)').text( $('.first').css("font-size") )
</script>
<script type="text/javascript">
//獲取尺寸甲馋,傳入CSS屬性組成的一個(gè)數(shù)組
//{width: "60px", height: "60px"}
var value = $('.first').css(['width','height']);
//因?yàn)楂@取的是一個(gè)對(duì)象埂奈,取到對(duì)應(yīng)的值
$('p:eq(2)').text( 'widht:' + value.width + ' height:' +value.height )
</script>
</br></br></br>
<h3>設(shè)置css屬性</h3>
<div class="fourth">設(shè)置顏色設(shè)置文字尺寸</div>
<div class="fifth">設(shè)置顏色設(shè)置文字尺寸</div>
<div class="sixth">通過回調(diào)設(shè)置新的值</div>
<div class="seventh">同時(shí)設(shè)置多少個(gè)樣式</div>
<script type="text/javascript">
//多種寫法設(shè)置顏色
$('.fourth').css("background-color","red")
$('.fifth').css("background-color","yellow")
</script>
<script type="text/javascript">
//多種寫法設(shè)置字體大小
$('.fourth').css("font-size","15px")
$('.fifth').css("fontSize","0.9em")
</script>
<script type="text/javascript">
//獲取到指定元素的寬度,在回調(diào)返回寬度值
//通過處理這個(gè)value定躏,重新設(shè)置新的寬度
$('.sixth').css("width",function(index,value){
value = value.split('px');
return (Number(value[0]) + 50) + value[1];
})
</script>
<script type="text/javascript">
//合并設(shè)置,通過對(duì)象傳設(shè)置多個(gè)樣式
$('.seventh').css({
'font-size':"15px",
"background-color":"#40E0D0",
"border":"1px solid red"
})
</script>
</body>