我希望两个togglePanels()中的一个能够工作,但它们没有?
<template>
<core-drawer-panel forceNarrow>
</core-drawer-panel>
</template>
<script>
var t = document.querySelector('template');
t.querySelector('core-drawer-panel').togglePanel()
t.shadowRoot.querySelector('core-drawer-panel').togglePanel()
</script>
另请注意,在我的控制台中它显示#document-fragment而不是#shadowRoot,因为我无法将其包装在聚合物元素中,因此其他js框架不会中断。
编辑:原来我需要做document.querySelector('core-drawer-panel').togglePanel()
但是这让我遇到问题核心抽屉面板还没有准备好。会问另一个问题。
答案 0 :(得分:1)
我怀疑问题在于您没有等待聚合物就绪事件,因此模板尚未扩展。
<script>
// need to wait for initialization to complete
document.addEventListener('polymer-ready', function() {
var t = document.querySelector('template');
t.querySelector('core-drawer-panel').togglePanel()
t.shadowRoot.querySelector('core-drawer-panel').togglePanel()
});
</script>
答案 1 :(得分:1)
默认<template>
不已插入您的可见DOM。这就是您在页面中看不到任何内容的原因。
您应首先附加template
,然后等待页面加载。就这样做:
<div id="insertTemplateHere">
<template>
<core-drawer-panel forceNarrow></core-drawer-panel>
</template>
</div>
<script>
// with jQuery: wait until page is ready
$(document).ready(function() {
// grab the element, where you want to insert the template
var page = document.querySelector('#insertTemplateHere');
// grab the template itself and read the whole content into `clone`
var template = document.querySelector('template');
var clone = document.importNode(template.content, true);
// append the content into the previously grabbed element
page.appendChild(clone);
// now use the element within the template
template.querySelector('core-drawer-panel').togglePanel();
// you don't need the shadowRoot, since you don't have any
// template.shadowRoot.querySelector('core-drawer-panel').togglePanel();
});
// native: wait until page is ready (works on ~90% of all global browsers used)
document.addEventListener("DOMContentLoaded", function(event) {
// grab the element, where you want to insert the template
var page = document.querySelector('#insertTemplateHere');
// grab the template itself and read the whole content into `clone`
var template = document.querySelector('template');
var clone = document.importNode(template.content, true);
// append the content into the previously grabbed element
page.appendChild(clone);
// now use the element within the template
template.querySelector('core-drawer-panel').togglePanel();
// you don't need the shadowRoot, since you don't have any
// template.shadowRoot.querySelector('core-drawer-panel').togglePanel();
});
</script>
请注意:<template>
的内容没有隔离。只有<core-drawer-panel>
带来了自己的影子根。