[英]Style reflection in nested polymer based Custom Element from parent <div>
我目前正在評估Polymer作為使用自定義元素的一種選擇,到目前為止,我對該功能印象深刻。我的JavaScript編碼技能有些缺乏,所以請耐心等待。
自定義元素是否可以通過嵌入自定義元素的Div標簽,樣式或CSS接收通知或更改。 換句話說,有沒有一種特定的方式可以讓我知道對象嵌入其中的父節點的更改,例如下面的示例,使用簡單的JavaScript像:
document.querySelector('#test').style[['top','left','right','width','height','bottom'] [Math.floor(Math.random()*5)]]=Math.floor(Math.random()*100);
我希望上面的調用將允許更改傳播到所有嵌套自定義元素。
<div id="test" style="top: 400; left: 50; width: 200; height: 300;">
<x-foo></x-foo>
<x-foo></x-foo>
<x-foo></x-foo>
</div>
任何幫助表示贊賞。 謝謝。
您在詢問一些不同的問題,但是我想您正在追求的是對x-foo進行樣式化,即樣式與父元素樣式相同的子項? 對於靜態樣式,很容易做到:
這很容易在CSS中完成:
<style> #test > x-foo { top: 400 left: 50; width: 200; } </style> <div id="test" class="theme"> <x-foo></x-foo> ... </div>
x-foo
元素本身可以定義:host-context()
樣式規則 ,該規則根據其所在的上下文來設置樣式:
:host-context(.theme) { /* Styles applied if an ancestor has the class "theme" */ }
對於動態生成的樣式(不可繼承的樣式),您必須將其應用於每個元素。 實際上,這與不使用Web組件所需要做的沒什么不同。 您還可以在父節點上設置MutationObserver
來檢測對style
屬性的更改。
將px放在每個值或其他比例尺旁邊。
<div id="test" style="top: 400px; left: 50px; width: 200px; height: 300px;">
如果這樣做很復雜,這肯定可以解決:
var test = document.querySelector('#test');
childrenInheritStyles(test);
function childrenInheritStyles(parent){
var children = parent.children;
var cstyles = parent.getAttribute('style');
for(var i=0; i<children.length; i++){
(function(c){
cstyles.replace(/([^:]+):([^;]+);/g, function(m, g1, g2){
c.style[g1.trim()] = g2.trim();
});
})(children[i]);
}
}
那就是如果您堅持以編程方式進行操作。
或者您可以使用以下命令:
var test = document.querySelector('#test');
childrenInheritStyles(test);
function childrenInheritStyles(parent){
var children = parent.children;
var cstyles = parent.getAttribute('style');
for(var i=0; i<children.length; i++){
children[i].style.cssText = cstyles;
}
}
第二種方法將替換所有樣式,因此取決於您要的內容。
無法自然地做到這一點。 如果您想要這種繼承,則必須對其進行編程或使用一個庫。
至於查看樣式何時更改,您將使用ebidel的有關MutationObservers的答案,或者您可以更改以上代碼以進行更改和傳播樣式。
我可以建議閱讀一下style屬性。 關於Javascript樣式屬性
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.