2015-10-21 34 views
0

我正在嘗試使用JavaScript/JQuery編輯css值。我有一個variable我創造,我想給它分配是這樣的:使用JavaScript/JQuery應用css值

var amount = 200; 
$("p").css({"background-color": "yellow", "font-size": "amount%"}); // 200% 

它僅適用的顏色,不是字體大小。我做錯了什麼,我該如何解決?

這裏有一個JSFiddle,這裏是代碼:

$(document).ready(function(){ 
 
    $("button").click(function(){ 
 
     
 
     var amount = 200; 
 
     $("p").css({"background-color": "yellow", "font-size": "amount%"}); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<body> 
 

 
<h2>This is a heading</h2> 
 

 
<p style="background-color:#ff0000">This is a paragraph.</p> 
 
<p style="background-color:#00ff00">This is a paragraph.</p> 
 
<p style="background-color:#0000ff">This is a paragraph.</p> 
 

 
<p>This is a paragraph.</p> 
 

 
<button>Set background-color of p</button> 
 

 
</body>

+0

變化' 「量%」''到量+ 「%」' – Griffith

回答

0

"amount%"將字符串 「量%」 的價值。但你想要的是amount + "%",改變了以200%

$(document).ready(function(){ 
 
    $("button").click(function(){ 
 
     
 
     var amount = 200; 
 
     $("p").css({"background-color": "yellow", "font-size": amount+"%"}); 
 
    }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<body> 
 

 
<h2>This is a heading</h2> 
 

 
<p style="background-color:#ff0000">This is a paragraph.</p> 
 
<p style="background-color:#00ff00">This is a paragraph.</p> 
 
<p style="background-color:#0000ff">This is a paragraph.</p> 
 

 
<p>This is a paragraph.</p> 
 

 
<button>Set background-color of p</button> 
 

 
</body>

+0

什麼時候應該使用' '$''? – Jessica

+0

我真的不明白你的意思,但$是jQuery的函數名稱,當你想選擇和找到你使用它的文檔中的一些東西時,它返回jQuery的對象。 – Omidam81