从 Javascript 设置浮点值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3443379/
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-10-25 01:11:33  来源:igfitidea点击:

setting the float value from Javascript

javascripthtmlcsscss-float

提问by Mala

I'm having trouble setting something to float right in JS. My code is as follows:

我在 JS 中设置一些东西浮动的问题。我的代码如下:

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. Firebug shows no trace of the float. There are no errors or warnings in the Error Console.

元素的背景确实是红色的,加载页面时会提示“正确”。然而 div 没有正确浮动。Firebug 没有显示浮动的痕迹。错误控制台中没有错误或警告。

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) 中以亮红色突出显示

回答by Daniel Vassallo

The standard way to set the float style in JavaScript is to use the cssFloatproperty:

在 JavaScript 中设置浮动样式的标准方法是使用cssFloat属性:

closebutton.style.cssFloat = 'right';

That works in all browsers, but not in IE, which expects the styleFloatproperty instead. Therefore you can either detect the browser, and apply the appropriate property, or else set them both:

这适用于所有浏览器,但不适用于 IE,它需要该styleFloat属性。因此,您可以检测浏览器并应用适当的属性,或者同时设置它们:

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

Note that floatis a reserved word in JavaScript, and cannot be used in the dot notation. The same applies for class, for example, which is another reserved word. That's why there is a different name for CSS properties that conflict with JavaScript reserved words (Source).

请注意,这float是 JavaScript 中的保留字,不能用在点符号中。class例如,这同样适用于另一个保留字。这就是与 JavaScript 保留字 ( Source)冲突的 CSS 属性的不同名称的原因。

Further reading:

进一步阅读:

回答by Ryan Kinal

Instead of closebutton.style.float, use closebutton.style.cssFloat

而不是closebutton.style.float,使用closebutton.style.cssFloat

Reference: W3C Style Object Reference

参考:W3C 样式对象参考