How do I put a variable in a string using javascri

2020-05-04 22:57发布

How do I put a variable in a string in JavaScript?

Example:

$('#contactForm').animate({"marginLeft": "+=680px"}, "slow");

I would like to use in a variable instead of 680px, is there a way to do this?

4条回答
ゆ 、 Hurt°
2楼-- · 2020-05-04 23:29
var theWidth = "680px"
$('#contactForm').animate({marginLeft: "+=" + theWidth}, "slow");
查看更多
Summer. ? 凉城
3楼-- · 2020-05-04 23:30
var size = "680px";
$('#contactForm').animate({"marginLeft": "+="+size}, "slow");
查看更多
Deceive 欺骗
4楼-- · 2020-05-04 23:44

As with most languages that don't have sigals, you can't perform interpolation, you have to concatenate multiple strings.

"foo" + "bar" + "baz"
"foo" + string_var + "baz"
"+=" + string_var + "px"
查看更多
唯我独甜
5楼-- · 2020-05-04 23:44

You can use the + operator to concatenate your value in a variable to the "+=" string:

$('#contactForm').animate({"marginLeft": "+=" + size}, "slow");
查看更多
登录 后发表回答