聚合物:检测自定义元素外部的单击
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了聚合物:检测自定义元素外部的单击相关的知识,希望对你有一定的参考价值。
我有一个自定义元素,并希望检测它之外的点击。例如
<dom-module id="simple-element">
<style>
</style>
<template>
<content></content>
</template>
</dom-module>
<script>
(function() {
Polymer({
is: 'simple-element',
listeners: {
'tap': 'regularTap'
},
regularTap: function() {
console.log("i was tapped");
}
});
})();
</script>
是否有一个我可以收听的事件会告诉我用户何时点击了该元素?谢谢。
答案
沿着这些方向的东西应该做你想要的:
window.addEventListener('click', (e) => {
var target = event.target;
while(target != this && target != document.body) {
target = Polymer.dom(target).node.domHost.parentNode;
// might need some additional steps to get the parent from inside custom elements
// don't know by heart
}
if(target == this) {
// inside element
} else {
// outside element
}
});
另一答案
修改了代码,使其实际工作:
var that = this;
window.addEventListener("click", function(e){
var target = e.target;
while (target != that && target != document.body) {
target = Polymer.dom(target).node.parentElement;
}
if (target == that) {
console.log("inside element");
} else {
console.log("outside element");
}
});
另一答案
你可以使用这样的行为:
<script>
/** @polymerBehavior Polymer.HarleyClickOutsideBehavior */
Polymer.HarleyClickOutsideBehavior = {
ready: function () {
// bind listener method
this.clickOutsideListenerBinded = this._clickOutsideListener.bind(this)
},
detached: function () {
this._clickOutsideUnlisten()
},
clickOutsideListen: function () {
// run this method to start listening
this._clickOutsideUnlisten()
window.addEventListener('click', this.clickOutsideListenerBinded, false)
},
_clickOutsideUnlisten: function () {
window.removeEventListener('click', this.clickOutsideListenerBinded, false)
},
_clickOutsideListener: function (ev) {
// check if the user has clicked on my component or on my children
var isOutside = !ev.path.find(function (path) {
return path === this
}.bind(this))
if (isOutside) {
this.onClickOutside()
this._clickOutsideUnlisten()
}
},
onClickOutside: function () {
// overwrite this method to be notified
}
}
</script>
另一答案
我发现一个更简单的解决方案还没有在所有浏览器上测试它,但是有道理。因此,我向窗口添加了一个全局侦听器,并为自定义元素添加了一个侦听器。这样点击里面会调用两者,点击外面只会调用全局..
listenToClickOutside() {
this.addEventListener("click", thisClick, false);
window.addEventListener("click", windowClick, false);
var clicksInside = 0;
var thisRef = this;
function thisClick() {
clicksInside++
}
function windowClick(event) {
clicksInside--;
if (clicksInside < 0) {
thisRef.removeEventListener("click", thisClick, false);
window.removeEventListener("click", windowClick, false);
// CLICKED outside
}
}
}
以上是关于聚合物:检测自定义元素外部的单击的主要内容,如果未能解决你的问题,请参考以下文章