2014-04-30 35 views
-1

我有類和字符串。 我怎樣才能把這個字符串從JavaScript到CSS?如何將字符串添加到類中javascript(jquery)

/*css*/ 
.new{ 
} 
/*javascript*/ 
var k='margin-top: 10px;'; 

如何將字符串k放入類new?

+1

這是不是很清楚你問什麼?你是想添加一個樣式標籤,還是隻在每個元素上添加一個樣式或一個樣式? – adeneo

+0

嘗試使用'.css()'... – Bhavik

+0

我想爲數字設置margin-top,例如 – George

回答

0

也許你想要這樣的東西?

fiddle

HTML

<div class="new"> 
    <input id="amount"> 
</div> 

CSS

.new { 
    margin-top: 10px; 
    background-color: blue; 
} 

JS

$("#amount").keyup(function(){ 
    $(".new").css("margin-top", parseInt($("#amount").val())) 
}).keyup(); 

無論何時在輸入框中輸入內容時,都會更改margin-top中類別爲.new的任何元素。如果你不想用戶輸入,你可以只使用$(".new").css("margin-top", yourValue);

0

假設你有new類元素,你的CSS內容如下:

.new { 
    margin-top: 10px; 
} 

然後,您可以應用所需的類使用JavaScript(jQuery的)這些元素:

$('.new').removeClass("new"); //Remove all 'new' classes 
$(element).addClass("new"); //Add 'new' class to just that 1 element. 
相關問題