perché this.style[property]
ottiene una stringa vuota? il mio codice è:
Demo #test{ height:100px; } .tclass{ width:100px; } function $(ID){ var element=document.getElementById(ID||'nodId'); if(element){ element.css=css; } return element; } function css(prop,value){ if(value==null){ return this.style[prop]; } if(prop){ this.style[prop]=value; } return true; } window.onload=function(){ var element=$("test"); alert(element.css("height")+","+element.css("width")+","+element.css("background")); //alert ,,#ccc }; Test
questo avviso di codice ,,#ccc
, ma voglio ottenere 100px,100px,#ccc
, cosa c’è di sbagliato in me? chi può aiutarmi?
aggiornare
Ho cambiato la funzione CSS, ora può funzionare bene:
function css(prop,value){ if(value==null){ var b = (window.navigator.userAgent).toLowerCase(); var s; if(/msie|opera/.test(b)){ s = this.currentStyle }else if(/gecko/.test(b)){ s = document.defaultView.getComputedStyle(this,null); } if(s[prop]!=undefined){ return s[prop]; } return this.style[prop]; } if(prop){ this.style[prop]=value; } return true; }
La proprietà .style
serve per ottenere gli stili che sono stati posizionati direttamente sull’elemento. Non calcola gli stili dai tuoi fogli di stile.
Vedi getComputedStyle()
.
Gli elementi non hanno un’altezza o una larghezza CSS specificata.
Nota che stai cercando di ottenere le dimensioni “richieste”, non le dimensioni effettive. L’uscita quindi è corretta.
Se vuoi ottenere le dimensioni efficaci , usa i metodi jQuery width()
e height()
. Vedi http://api.jquery.com/width/