Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
701 views
in Technique[技术] by (71.8m points)

html - setting the float value from Javascript

I'm having trouble setting something to float right in 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. Firebug shows no trace of the float. 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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

closebutton.style.cssFloat = 'right';

That works in all browsers, but not in IE, which expects the styleFloat property instead. 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. 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).

Further reading:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...