cambiar las propiedades CSS3 (prefijo) específicas del navegador en JavaScript

So I'm trying to dynamically change the style of a div with javascript, which is normally no big deal except that I'm trying to change some CSS3 properties which have a prefix, i.e. minus (-) in the name... and of course, that means something else entirely in javascript...

so I've got this going on in my javascript:

r += 1;
document.getElementById('someDiv').style.transform = "rotate(" + r + "deg)";

and my div's style property looks like this:

transform: rotate(30deg);
-ms-transform: rotate(30deg); /* IE 9 */
-webkit-transform: rotate(50deg); /* Safari and Chrome */
-o-transform: rotate(30deg); /* Opera */
-moz-transform: rotate(30deg); /* Firefox */

so that javascript works fine to change the "transform" property, but how would I change the rest of them? because doing something like this won't work:

document.getElementById('someDiv').style.-ms-transform = "rotate(" + r + "deg)";

because the javascript reads the "-" as syntax error :(

pensamientos?

preguntado el 01 de febrero de 12 a las 22:02

4 Respuestas

En vez de -, make the next letter uppercase: style.MozTransform.
(al igual que style.backgroundColor)

Note that IE incorrectly uses msTransform con minúsculas m.

Respondido 02 Feb 12, 02:02

De hecho, creo que es msTransform. - Niet the Dark Absol

Well given that document.body.style.MsTransform no está definido y document.body.style.msTransform is an empty string, I'd have to say I'm right here. - Niet the Dark Absol

Ah yes, Awesome! Thanks so much! I haven't tried on IE or Opera, but this seems to work great on Chrome, Safari, and FireFox :) - Nick Briz

In javascript you can access object property trought two ways : dot notation or array notation. In particular when you have special chars in the property name, use array notation :

document.getElementById('someDiv').style['-ms-transform'] = "rotate(" + r + "deg)";

Then you need to insure that the property is right for the browser, I strongly recommend you to use a javascript lib like jQuery, Mootools, etc if you wana win some time and prevent some frustration that web developpers had before these great tools...

Respondido 02 Feb 12, 02:02

Because the Javascript property is called msTransform. That will create a new property that the browser will ignore. - SLaks

Use jquery and just change classes

 $("p").removeClass("myClass noClass").addClass("yourClass");

Respondido 02 Feb 12, 02:02

I wish I could up this twice! - skybondsor

If you already have the style en línea you can ignore the prefix and change the degrees. An element's style.cssText is read and writable.

var sty=document.getElementById('someDiv').style;

sty.cssText= sty.cssText.replace(/rotate\([^)]+/,'rotate(30');

Respondido 02 Feb 12, 04:02

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.