附近有几个物体,指向它们中的每一个都会出现一个带有动画的提示(一个列表ul,它们li一个接一个地平滑出现)。由于有很多元素并且用户可以快速超越它们,我决定以debounce(f, 150ms). 但是现在,如果您将鼠标随机移动到对象上并且原则上不与任何东西交互,则会出现最后一个受影响对象的提示(这是合乎逻辑的),因为它的debounce工作时间比工作时间晚.stop().fadeOut(). 并且有时会出现一个bug,如果你拉手,例如从一个对象到另一个对象(我这里没有重新创建它,也许有人会弄清楚,如果没有,我会尝试举个例子),然后提示出现在光标下,但由于它与 object 重叠,这表明它立即消失并且鼠标再次位于对象上,提示出现并且一切都在循环中。
function debounce(f, ms) {
let timer = null;
return function (...args) {
const onComplete = () => {
f.apply(this, args);
timer = null;
}
if (timer) {
clearTimeout(timer);
}
timer = setTimeout(onComplete, ms);
};
}
function renderHint() {
$('#hint').stop().append('123').fadeIn('100');
}
let renderHintDebounce = debounce(renderHint, 150);
$('.block').on('mouseenter', function(e) {
$('#hint').empty();
$(this).mousemove(function(pos) {
$("#hint")
.css('left', (pos.pageX + 50)+'px')
.css('top', (pos.pageY - 30)+'px');
});
renderHintDebounce();
});
$('.block').on('mouseleave', function(e) {
$('#hint').stop().fadeOut(100).queue(function() {
$(this).empty().dequeue();
})
});
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
width: 100vw;
}
.block {
width: 100px;
height: 100px;
background: red;
}
#hint {
position: absolute;
display: none;
background: #eee;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="block"></div>
</div>
<div id="hint">123</div>
添加. 如果工具提示没有按位置添加,即 添加 50 和 30 像素,然后工具提示出现和消失的错误与我的错误相似。
这样的界面“功能”,虽然乍一看很简单,但实际上实现起来相当困难。是的,显示/隐藏很容易,但在不同的浏览器和堆栈中实现稳定和“漂亮”的工作却非常困难。
使用社区的经验,例如: