简体   繁体   English

将变量传递给javascript的CSS样式

[英]passing a variable into style css for javascript

I'm trying to set a margin-left using a variable in JavaScript. 我正在尝试使用JavaScript中的变量设置左边距。 Is this possible? 这可能吗? How can this be done? 如何才能做到这一点?

The margin left needs to be the clientWidth of the text: 左边距必须为文本的clientWidth:

var hoverBubble = document.getElementById(id);
var linkWidth = link.clientWidth + 1;
hoverBubble.style.margin-left = linkWidth + 'px';

It is possible, you just have to camelCase style properties. 有可能,您只需要驼峰式样式属性即可。

hoverBubble.style.marginLeft = linkWidth + 'px';

You just can't use an hyphen (minus sign) as in the question. 您只是不能在问题中使用连字符(减号)。

Otherwise the interpreter will "think" that you have a subtraction operation in the left-side of the assignment, which results in a syntax error. 否则,解释器会“认为”您在分配的左侧进行了减法运算,这会导致语法错误。

You can see that error on proper debugging tools, such as Chrome Dev Tools (F12 in Chrome and select console) or Firebug (Install Firebug and press F12 on Firefox). 您可以在适当的调试工具上看到该错误,例如Chrome开发工具 (Chrome中为F12,然后选择控制台)或Firebug (安装Firebug并在Firefox中按F12)。

尝试这个

hoverBubble.style.marginLeft = linkWidth + 'px';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM