2014-11-24 26 views
0

如何使用jQuery更新元素的style參數?使用jQuery更新HTML元素樣式參數值

我有這樣的HTML代碼:

<div id="template" style="width:200px; height:200px; border:none;">blabla...</div> 

現在我試圖用這樣的:

$('#template').attr('style', '...'); 

這:

$('#template').prop('style', '...'); 

...但不工作。

jQuery中有沒有工作解決方案?

更新:我不想更新元素的樣式。我只想直接覆蓋stlye參數的值。

+0

$('#template')。css('width','100px');你試過這個嗎? – Sai 2014-11-24 19:49:21

+0

是的,但我不想更新元素的'css'參數。我只想直接覆蓋'style'參數的值。 – netdjw 2014-11-24 20:04:58

回答

0

.css()是使用jQuery操作樣式的最佳方法。

Documentation

你舉的例子可以做的:

$('#template').css({'font-size', '2em'});

2

更新現有的風格,你可以使用jQuery .css()

$('#template').css('color', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="template" style="width:200px; height:200px; border:none;">blabla...</div>

jquery .attr()將自定義屬性添加到元素。在您的OP它將改變屬性style新:

$('#template').attr('style', 'color:red;border: solid 1px');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="template" style="width:200px; height:200px; border:1px solid;">blabla...</div>

正如你所看到的將只保留了新的。同樣的方法將在您的OP中運行.prop()

0

您必須使用jQuery的css方法,如果你想在你需要嘗試這樣的東西的時間來編輯幾個屬性:

$('#template').css({ 
    'font-size' : '10px', 
    'width' : '30px', 
    'height' : '10px' 
}); 
0

而不是更新的,覆蓋!

忽略聲明的內容,並且在運行時,jquery將覆蓋使用新值設置的內容。所以,不要嘗試定位樣式屬性,只是過度加載它。

$('#template').css({'color': 'blue', 'width':'200px'}); 

0

,你可以使用jQuery的CSS API這是指:http://api.jquery.com/css/

$('#template').css('width', '100px'); // to change the width 

,或者如果你有一個以上的CSS樣式屬性來更改然後,創建一個類,並聲明你所有的風格,然後使用jQuery的addClass API參考:http://api.jquery.com/addclass/

css: 
    .someClass{ width:100px; opacity:0.5; color:blue} 

jquery: 
    $('#template').addClass('someClass'); 

希望這可以幫助

0
$(document).on('click', '#template', function() { 
    $('#template').css({'color' : '#e8e8e8', 'width' : '25em'}) 
)}; 
相關問題