[英]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.