sai*_*web 5 html javascript css jquery
我已将一个mouseenter事件与页面上的某些元素绑定在一起,我正在检查页面是否已加载,然后才允许 mouseenter 的实际功能运行。一切正常,但问题是,如果用户在页面加载之前已经将光标放在元素上,则用户将被迫首先移出 div,然后再次将光标移动到 div 内以触发事件,这使得这很尴尬。
有没有一种方法可以检查光标在页面加载时的位置,例如光标悬停在哪个元素上并相应地触发 mouseenter 事件?
我附上了一个片段,以便更好地理解我的问题。
提前致谢。
let pageLoaded;
/* assuming page load takes 3 seconds*/
window.onload = () => setTimeout(() => pageLoaded = true, 3000)
$(document).ready(() => {
$('#box').mouseenter(() => {
/* continue only if the page has been loaded */
if (!pageLoaded)
return;
$('body').append('mouse entered after page load <br>')
})
})Run Code Online (Sandbox Code Playgroud)
#box {
height: 150px;
width: 150px;
background-color: green;
margin:10px;
cursor:pointer;
float: left;
}
p {
font-style: italic;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">
</div>
<p> I want the mouseenter event to fire (on page load ~ "3 seconds here"), if the cursor was already placed inside the green box before the page loaded. </p>Run Code Online (Sandbox Code Playgroud)
** 编辑答案 ** 由于隐藏该框不是一个选项,因此请使用一个布尔值,在页面加载之前使用 mouseenter 和 mouseleave 跟踪用户是否位于该框上。然后,如果页面加载后布尔值为 true,则手动调用与 mouseover 事件相同的逻辑。然后删除 mouseenter 和 mouseleave 监听器。
let pageLoaded;
let insideBox = false;
/* assuming page load takes 3 seconds*/
window.onload = () => setTimeout(function() {
pageLoaded = true;
if (insideBox) {
// Manually call the mouseover logic here
$('body').append('mouse entered BEFORE page load <br>')
}
$('#box').off('mouseenter').off('mouseleave')
}, 3000)
$(document).ready(() => {
$('#box').on('mouseenter', function() {
insideBox = true;
})
$('#box').on('mouseleave', function() {
insideBox = false;
})
$('#box').mouseover(() => {
/* continue only if the page has been loaded */
if (!pageLoaded)
return;
$('body').append('mouse entered after page load <br>')
})
})Run Code Online (Sandbox Code Playgroud)
#box {
height: 150px;
width: 150px;
background-color: green;
margin:10px;
cursor:pointer;
float: left;
}
p {
font-style: italic;
}Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">
</div>
<p> I want the mouseenter event to fire (on page load ~ "3 seconds here"), if the cursor was already placed inside the green box before the page loaded. </p>Run Code Online (Sandbox Code Playgroud)