简体   繁体   English

从Javascript设置浮点值

[英]setting the float value from Javascript

I'm having trouble setting something to float right in JS. 我无法在JS中设置一些东西。 My code is as follows: 我的代码如下:

var closebutton = document.createElement('div');
closebutton.style.styleFloat = "right";
alert(closebutton.style.styleFloat);
closebutton.style.background = "#f00";
closebutton.innerHTML = '<a href="">&#10006;</a>';
titlebar.appendChild(closebutton);

The background of the element is indeed red, and when loaded the page alerts "right". 元素的背景确实是红色,加载时页面警告“正确”。 Yet the div is not floated right. 然而,div并没有正确地浮动。 Firebug shows no trace of the float. Firebug没有显示浮动的痕迹。 There are no errors or warnings in the Error Console. 错误控制台中没有错误或警告。

I'm stumped! 我很难过!

Update: 更新:
As suggested, I have also tried: 正如所建议的那样,我也尝试过:

closebutton.style.float = 'right';

This also does not work, and is highlighted bright red in my text-editor (gedit) 这也不起作用,在我的文本编辑器(gedit)中突出显示为鲜红色

The standard way to set the float style in JavaScript is to use the cssFloat property: 在JavaScript中设置float样式的标准方法是使用cssFloat属性:

closebutton.style.cssFloat = 'right';

That works in all browsers, but not in IE, which expects the styleFloat property instead. 这适用于所有浏览器,但不适用于IE,后者需要使用styleFloat属性。 Therefore you can either detect the browser, and apply the appropriate property, or else set them both: 因此,您可以检测浏览器,并应用适当的属性,或者将它们设置为:

closebutton.style.styleFloat = 'right';
closebutton.style.cssFloat = 'right';

Note that float is a reserved word in JavaScript, and cannot be used in the dot notation. 请注意, float是JavaScript中的保留字,不能用于点表示法。 The same applies for class , for example, which is another reserved word. 这同样适用于class ,例如,这是另一个保留字。 That's why there is a different name for CSS properties that conflict with JavaScript reserved words ( Source ). 这就是为什么CSS属性的名称与JavaScript保留字( Source )不同的原因。

Further reading: 进一步阅读:

Instead of closebutton.style.float , use closebutton.style.cssFloat 而不是closebutton.style.float ,请使用closebutton.style.cssFloat

Reference: W3C Style Object Reference 参考: W3C样式对象参考

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

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