【问题标题】:Detecting mouse cursor type change in a webpage检测网页中的鼠标光标类型变化
【发布时间】:2013-01-26 17:02:31
【问题描述】:

当鼠标光标悬停在不同的页面元素上时,是否会触发任何事件?

最好是这样的事件:

window.onmousecursorchange = function(e) {
    // e would contain information about the cursor
    // eg. e.type could contain 'text','pointer', etc..
}

注意:解决方案不应涉及jQuery或其他库

更新:

“可能重复”的问题是用 jQuery 标记的,事实上所有的答案(没有一个能解决问题)都是基于 jQuery。我正在寻找一个纯 JavaScript 解决方案。如果版主认为这不足以让这个问题保持开放,请随时关闭。

【问题讨论】:

标签: javascript html dom-events


【解决方案1】:

你可以试试这个:

document.addEventListener('mouseover',function(e){
    var cursor = e.target.style.cursor;
    console.log(cursor);
});

它使用事件冒泡来提高性能并节省代码。

【讨论】:

    【解决方案2】:

    是的,事件onmouseenter

    $('*').mouseenter(function(){
        var currentCursor = $(this).css('cursor') ;
        console.log( currentCursor );
    });
    

    【讨论】:

    • 只有在元素预先设置了 style.cursor 属性的情况下才有效?例如。 jsfiddle.net/jrHcY 两个项目都返回“自动”
    • @FelixKling 你是对的似乎有点不一致,因为它在 Chrome 24 上记录“自动”
    【解决方案3】:
    $(function(){
    
        $('*').hover(function(){
            $(this).data('hover',1); //store in that element that the mouse is over it
        },
    
        function(){
            $(this).data('hover',0); //store in that element that the mouse is no longer over it
        });
    
        window.isHovering = function (selector) {
            return $(selector).data('hover')?true:false; //check element for hover property
        }
    });
    

    【讨论】:

    • 这不会检测到课程的变化,并且使用了很多难以复制的 jQuery 东西(OP 没有提到 jQuery)。
    • 我只是粘贴我搜索的内容。我只是想帮忙。那么如果它是错误的那么这个人的答案是不正确的stackoverflow.com/questions/3395293/…。这个人得到了最好的答案,多么悲伤
    • 首先你不应该复制另一个答案。如果另一个答案确实适合,您应该投票关闭该问题或将该问题标记为与另一个问题重复。其次,另一个问题是不同的(因此答案不适合这里)。一个是问如何检测光标形状变化,另一个是问如何检测光标是否悬停在给定元素上。
    • 是的,对不起,我忘了放链接,我只是直接放了它,然后转到其他问题。我不知道如何投票关闭,这是我第一次加入stackoverflow。我只是在开心地回答:)
    猜你喜欢
    • 2011-07-15
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    相关资源
    最近更新 更多