Javascript 带有变量和多个值的 jQuery .css() 函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8462040/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:06:18  来源:igfitidea点击:

jQuery .css() function with variables and multiple values

javascriptjquerycsssyntax

提问by technopeasant

Weird little snafu. I'm using jQuery's .css()method to change the size of text (long story; no, I can't use media queries) using a variable and I need to add emto it. I'm not sure what the syntax is because there are multiple values for the CSS change.

奇怪的小混混。我正在使用 jQuery 的.css()方法来使用变量更改文本的大小(长话短说;不,我不能使用媒体查询),我需要添加em到它。我不确定语法是什么,因为 CSS 更改有多个值。

To illustrate:

为了显示:

This works perfectly. It adds emto the calculated value of victore:

这完美地工作。它增加em了 的计算值victore

$('h1').css('font-size', victore + 'em');

This doesn't:

这不会:

$('h1').css({
    'font-size':victore + 'em',
    'line-height':vignelli + 'em';
});

The emneeds quotes... but so does the value. Wrapping it in parens didn't work

em需要引号...但这样做的价值。将它包装在括号中不起作用

回答by James Montagne

You shouldn't have the quotes around the whole thing:

你不应该在整件事上加引号:

$('h1').css({
    'font-size': victore + "em",
    'color':'red'
});

回答by Phil Klein

The font-size value is required to be a string, but that string can be the result of an expression, in your case victore + 'em'should result in the appropriate string.

font-size 值必须是一个字符串,但该字符串可以是表达式的结果,在您的情况下victore + 'em'应该产生适当的字符串。

$('h1').css({ 
    'font-size': victore + 'em', 
    'color': 'red' 
});

回答by Brigand

Here's a fiddle.

这是一个小提琴

$('h1').css({
    'font-size':victore + "em",
    'color':'red'
});