简体   繁体   English

如何进行鼠标悬停/一次性检查?

[英]How can I have a mouseover/in one off check?

How can I test if a mouse is within a given div? 如何测试鼠标是否在给定的div中? I know how to use events to do something when it occurs but is it possible to check it on pageload only? 我知道如何使用事件在事件发生时做一些事情,但是是否可以仅在页面加载时检查事件?

What I want to do is smething like: 我想做的是这样的:

    if(mouse is in specified div) {
        check = true;
    } else {
        check = false;
    }

Thanks, Denis 谢谢,丹尼斯

You can put the event at the top of your site's page like so (which would require the .js files to load in the header): 您可以像这样将事件放在网站页面的顶部(这需要将.js文件加载到标题中):

$('element').mouseover( function() {
    function_to_execute(); 
});

And then, at the bottom of your page, just before the end </body> have it say: 然后,在页面底部</body>末尾说:

<script type="text/javascript>
    $('element').unbind();
</script>

To keep it from activating after page load. 为了防止它在页面加载后被激活。 If that's what you wanted. 如果那是您想要的。 I wasn't entirely clear based on your question. 根据您的问题,我并不清楚。

This will work on the first hover over the div and then never again. 这将首先在div上悬停,然后再也不会起作用。 Do you want to check only if the mouse is over the div immediately on page load or just the first time the mouse hovers over it? 您是否只想在页面加载时立即将鼠标悬停在div上,还是仅将鼠标第一次悬停在div上进行检查? If you want the former, it might be a little trickier, but check out this SO post to see how to do it. 如果要使用前者,可能会有些棘手,但是请查看这篇SO帖子以了解如何做。

$('div').hover(
  function() {
     alert('in the div');
  },
  function() {
     $(this).unbind();
  }
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM