按钮悬停在滚动后



$("button").on("click", () => {
console.log($("button").is(":hover"));
window.scrollTo(0,0);
console.log($("button").is(":hover"));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button style="margin-top:600px;">
CLICK
</button>

// method called on button click
showTab(n) {
this.tabs.each((idx, tab) => {
$(tab).hide();
});
$(this.tabs[n]).show();
this.currentTab = parseInt(n);
window.scrollBy(-100, -100);
window.scrollTo(0,0);
}

在该代码的末尾,NextButton.is(":hover")返回true,它也以按钮样式显示。我不明白为什么。什么好主意吗?有没有一种方法可以"解除焦虑"?按钮与jQuery?

函数调用是异步的。因此,在调用scrollTo(..)之后,console.log(..)会立即执行,同时仍然悬停在按钮上。

为了避免这种行为,你通常会使用回调函数,它在初始函数完成后被调用。

$("button").on("click", function(){
console.log($("button").is(":hover"));
$('html').animate({
scrollTop: 0
}, 500, function() {
// gets executed after the animation has finihsed
console.log($("button").is(":hover"));
});

})
button {
position:absolute;
top: 650px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>
CLICK
</button>

最新更新