2014-01-23 23 views
0

我試圖創建一個簡短的方式來填充一些CSS元素。 我想要一種快速設置元素樣式屬性的方法。如何擴展樣式對象

我可以(例如)做:

Element.prototype.set_box = function (left, top, width, height) 
    { this.style.left = left+"px"; this.style.top=top+"px"; 
    this.style.width = width+"px"; this.style.height = height+"px";   
    } 

obj = getElementById(id_name); 
obj.set_box (10,20,300,200); 

我想不是必須編寫代碼來訪問style對象,但訪問樣式對象本身,這樣的事情:

Element.style.prototype.set_box = function (left, top, width, height) 
    { this.left = left+"px"; this.top=top+"px"; 
    this.width = width+"px"; this.height = height+"px";   
    } 

Style.prototype.set_box = function (left, top, width, height) 
    { this.left = left+"px"; this.top=top+"px"; 
    this.width = width+"px"; this.height = height+"px";   
    } 

但是是不可能的。我有一個警告「未定義....」。 有什麼想法? 謝謝。

回答

0

正確的原型擴展爲:

CSSStyleDeclaration.prototype.set_box = function... 

一般情況下,發現了這一點,在控制檯上運行是這樣的:

[a known instance of the object].constructor 

例如:

document.body.style.constructor 
+0

太好了!非常感謝 ! – civiltomain