Pergunta

i've follow the w3c description for setting up the css properties of an element with javascript, but i cant figure how to do it with a json object.

my code is this :

var style = {
    position:'fixed',
    top:0,
    right:0,
    bottom:0,
    left:0,
    background:'red'
}


var el = document.getElementById( 'some_id' );
for( var key in style ){
    el.style.key = style[key]
}

but when a run my script i get "Uncaught TypeError: Cannot read property 'style' of null"

Foi útil?

Solução

Code example:

Object.assign(document.querySelector('.my-element').style, {
    position: 'fixed',
    top: 0,
    right: 0,
    bottom: 0,
    left: 0,
    background: 'red'
})

Example on JSFiddle:

https://jsfiddle.net/b6hexafL/4/

Outras dicas

This seems to work well if you want to generate one or more iframes on loading:

    var dir,name,ele,style,k,v;
    dir = ...
    name = ...
    ele = $(document.createElement("iframe"));
    $("#layout",parent.document).append(ele);
    ele.attr({
        src: dir +"/" +name +".html",
        id: dir +name
    });
    style = nset[dir].monitor[name].css;
    $.each(style,function(k,v){
        ele.css(k,v)
    });
    ele.load(function(){
        //next iframe or start function ... can use loaded frames
    });

with relevant part of nset like this:

 "lert": {
        "css":{
            "left": 100 ,
            "top": 0 ,
            "width": 320 ,
            "height": 480 ,
            "display": "none",
            "overflow": "hidden",
            "backgroundColor":"white"
        }
   }

You should write:

for (var key in style) { 
    el.style[key] = style[key]
}

Example Fiddle of what you are trying to implement:

for(var key in s) {
    el.style[key] = s[key]
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top