我试图在每次标记其内容时将输入元素聚焦在聚合物模板内。问题是在模板加载之前我无法选择输入元素。目前,我只是使用 setTimeout 在模板加载后 100 毫秒集中输入,但我想知道是否有更优雅的解决方案。此外,自动对焦属性不起作用,因为模板可能会多次取消标记和重新标记。现在,我的代码看起来像这样(这是在聚合物元素定义内):
Polymer({
// ...
showInput: false,
makeInputVisible: function() {
this.showInput = true;
var container = this.$.container;
setTimeout(function() {
container.querySelector("#input").focus();
}, 100);
},
});
<div id="container">
<template if="{{showInput}}">
<input id="input" is="core-input" committedValue="{{inputValue}}" />
</template>
</div>
但我更喜欢这样的东西:
Polymer({
// ...
showInput: false,
makeInputVisible: function() {
this.showInput = true;
},
focusInput: function() {
this.$.container.querySelector("#input").focus();
},
});
<div id="container">
<template if="{{showInput}}"
on-stamp="{{focusInput}}">
<input id="input" is="core-input" committedValue="{{inputValue}}" />
</template>
</div>
任何想法表示赞赏。
在 Polymer 1.0 中,模板在标记时会触发“dom-change”事件。然而,使用 dom-if 模板会带来显着的性能成本,因为它们需要操作 dom 树。这样做会更好:
<div id="container">
<input id="input" hidden="[[!showInput]]" value="{{inputValue::input}}">
</div>
observers: [
'_showInputChanged(showInput)',
],
_showInputChanged: function (showInput) {
if (showInput) {
this.$.input.focus();
}
},
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)