javascript 检测网页中的鼠标光标类型改变

snz8szmq  于 2023-01-29  发布在  Java
关注(0)|答案(4)|浏览(167)

当鼠标光标悬停在不同的页面元素上时,是否会触发任何事件?
理想的情况是这样的:

window.onmousecursorchange = function(e) {
    // e would contain information about the cursor
    // eg. e.type could contain 'text','pointer', etc..
}
    • 注意:解决方案不应涉及jQuery或其他库**
    • 更新**:

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

ndasle7k

ndasle7k1#

是,事件onmouseenter

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

cbjzeqam2#

你可以试试这个:

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

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

izkcnapc

izkcnapc3#

$(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
    }
});
yc0p9oo0

yc0p9oo04#

@Lickson的解决方案here只适用于内联样式,不适用于css文件中定义的游标。因此,您需要getComputedStyle

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

相关问题