我试图编写jQuery插件,将默认光标替换为必要的图像,但我遇到了 mouseleave 的问题。它不会触发,因为光标总是在子div之前并且永远不会离开它,因此光标永远不会变回默认值。
任何想法如何解决?
顺便说一下:jQuery mouseleave 的行为有点奇怪。只有当你离开你的div和所有的孩子时才会开火。
我的代码:
// 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 );
});
我的解决方案:
答案 0 :(得分:1)
我做了一些调整:
this
存储在变量中。<强>使用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);
答案 1 :(得分:0)
对于仍在寻找相似外观的任何人,请尝试以下操作(也许):
$('#selector').css('cursor', 'url("/path/your_image.png"), auto');
PS:在原始浏览器上不起作用!