gpt4 book ai didi

javascript - 使用 JavaScript/JQuery 应用 css 值

转载 作者:行者123 更新时间:2023-11-28 07:00:48 27 4
gpt4 key购买 nike

我正在尝试使用 JavaScript/JQuery 编辑 css 值。我有一个我创建的 variable,我想这样分配它:

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>

最佳答案

“amount%” 将是具有“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>

关于javascript - 使用 JavaScript/JQuery 应用 css 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33249842/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com