使用jQuery将光标更改为自定义图像

Changing cursor to custom image with jQuery

本文关键字:自定义 图像 jQuery 光标 使用      更新时间:2023-09-26

我正试图编写jQuery插件,将默认光标替换为必要的图像,但我在鼠标离开时遇到了问题。它不会触发,因为游标总是在子div之前,并且永远不会离开它,所以游标永远不会变回默认值。

演示

有什么办法吗?

顺便说一句:jQuerymouseleave的行为有点奇怪。只有当您离开div和所有childediv时,它才会启动。

演示2

我的代码:

// Plugin changing cursor before element
;
(function ($) {
    $.fn.changeCursor = function (cursorPicUrl, dx, dy) {
        function inFunction(e) {
            $cursor.show();
            return false;
        }
        function outFunction(e) {
            $cursor.hide();
            return false;
        }
        function moveFunction(e) {
            var x = e.clientX-100;
            var y = e.clientY-100;
            $cursor.css({
                "transform": "translate(" + x + "px," + y + "px)"
            });
        }
        var $cursor = $('<div id="#custom-cursor"></div>').css({
            /*cursor: none;*/
            width:      '150px',
            height:     '150px',
            background: 'url("' + cursorPicUrl + '") no-repeat left top',
            position:   'absolute',
            display:    'none',
            'z-index':  '10000'
        });
        this.append( $cursor )
            .on( "mouseenter", inFunction )
            .on( "mouseleave", outFunction )
            //.hover( inFunction, outFunction)
            .mousemove( moveFunction );
        return this;
    };
})(jQuery);
$(document).ready(function () {
    var url = 'http://placehold.it/150x150';
    $('#test-area').changeCursor( url );
});

更新

我在这里的独白:

jquery.change游标

我做了几个调整:

  1. this预先存储在变量中
  2. 将光标div附加到主体
  3. 将顶部/左侧属性添加到光标中

演示

Javascript:

(function ($) {
    $.fn.changeCursor = function (cursorPicUrl, dx, dy) {
        var elem = this;
        function inFunction(e) {
            $cursor.show();
            return false;
        }
        function outFunction(e) {
            $cursor.hide();
            return false;
        }
        function moveFunction(e) {
            var x = e.clientX;
            var y = e.clientY;
            $cursor.css({
                "transform": "translate(" + x + "px," + y + "px)"
            });
        }
        var $cursor = $('<div id="#custom-cursor"></div>').css({
            /*cursor: none;*/
            width:      '150px',
            height:     '150px',
            background: 'url("' + cursorPicUrl + '") no-repeat left top',
            position:   'absolute',
            top: '0',
            left: '0',
            display: 'none'
        });
        $('body').append( $cursor );
        elem.on( "mouseenter", inFunction )
          .on( "mouseleave", outFunction )
          .mousemove( moveFunction );
        return this;
    };
})(jQuery);

对于任何看起来仍然相似的人,试试这个(也许):

$('#selector').css('cursor', 'url("/path/your_image.png"), auto');

PS:在原始浏览器上不起作用!