我正在尝试编写 jQuery 插件,将默认光标替换为必要的图像,但我遇到了 mouseleave 问题。它不会触发,因为光标始终位于子 div 之前并且永远不会离开它,因此光标永远不会变回默认值。
DEMO
有什么解决办法吗?
顺便说一句:jQuery mouseleave 行为有点奇怪。仅当您离开您的 div 和所有子级 div 时它才会触发。
DEMO 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-cursor
最佳答案
我做了一些调整:
- 将
this
存储在前面的变量中。 - 将光标 div 附加到正文。
- 将顶部/左侧属性添加到光标。
DEMO
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);
关于javascript - 使用 jQuery 将光标更改为自定义图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26490698/