假设,我想要在点击特定颜色的气泡(1)时增加分数的游戏。如果出现的气泡没有点击,分数将会降低,甚至游戏将结束。
使用addEventListener 'click‘事件来征服数字1很容易,但是我怎么才能做到2呢?
发布于 2018-12-29 16:54:16
这取决于你的气泡的行为。正如@CertainPerformance所提到的,您可以使用setTimeout,但是当您谈论气泡时,我想象一个气泡将升向天空,因此您还可以使用Intersection Observer API来检测气泡何时离开视口,例如:
var bubble = document.getElementById('bubble');
var options = {
root: document.querySelector('#window'),
rootMargin: '0px',
threshold: 0
}
var callback = function(entries, observer) {
entries.forEach(entry => {
if (!entry.isIntersecting) {
bubble.parentNode.removeChild(bubble);
alert('You missed it!');
}
});
};
var observer = new IntersectionObserver(callback, options);
observer.observe(bubble);
bubble.addEventListener('click', function() {
observer.unobserve(bubble);
alert('Got it!');
bubble.parentNode.removeChild(bubble);
});#window {
background: blue;
border: 1px solid black;
height: 250px;
overflow: hidden;
position: relative;
width: 500px;
}
#bubble {
animation: fly 5s normal;
background: red;
border-radius: 20px;
height: 40px;
left: 150px;
position: absolute;
width: 40px;
}
@keyframes fly {
from {
top: 250px;
}
to {
top: -100px;
}
}<div id="window">
<div id="bubble"></div>
</div>
请记住,Internet Explorer不支持交叉点观察者API,对于不受支持的浏览器,您需要一个polyfill。
https://stackoverflow.com/questions/53953190
复制相似问题