2012-05-08 166 views
0

我試圖用圖像替換鼠標光標。jquery替換鼠標光標

我有以下的html:

<div id="content-bg"> 
    <img src="path"/> 
</div> 
<div id="mouse"></div> 

CSS:

#content-bg{ 
    background:url(../img/frontend/content-bg.png) top left no-repeat; 
    width: 968px; 
    height: 552px; 
    position:relative; 
} 

#mouse { 
    cursor: none; 
    width: 75px; 
    height: 76px; 
    background: url("../img/frontend/cross.png") no-repeat center; 
    position: absolute; 
    display:none; 
    top: 0; 
    left: 0; 
    z-index: 10000; 
} 

的javascript:

$(document).ready(function(){ 
    $('#content-bg').mouseout(function(){ 
      $('#mouse').hide(); 
      $(this).css("cursor","none"); 
      return false; 
    }); 
    $('#content-bg').mouseenter(function(){ 
      $('#mouse').show(); 
      return false; 
    }); 
    $('#content-bg').mousemove(function(e){ 
      var x = e.clientX - $(document).scrollLeft() - 37.5; 
      var y = e.clientY + $(document).scrollTop() - 38; 
      $('#mouse').css('left', x).css('top',y); 
    }); 
}); 

鼠標圖像是在正確的地方,但似乎閃爍,浮華。過渡並不像我想要的那麼順利。不知何故,似乎mouseout和mouseenter事件每次在content-bg div中移動鼠標時都會觸發。

任何想法如何解決這個問題?

感謝

+0

這是becaue鼠標DIV隱藏着'內容bg',所以鼠標「左」,然後重新輸入。您需要以其他方式完成任務,或者離開它... – gdoron

+0

您是否嘗試更改顯示圖像的偏移量?嘗試添加它,而不是去除半寬/高。沒有它,我不確定它會不會觸發mouseout,即使是因爲移動的div本身 –

+0

@gdoron但是,如果我把它的一半維數工作得很好......你能建議一個更好的方法或指向我有些文件好嗎? – jribeiro

回答

2

正如已指出了意見,你mouseout當鼠標懸停突然#mouse,因爲它似乎發生。

您需要手動取消這些事件:

$('#content-bg').mouseout(function(e){ 
     if($(e.relatedTarget).is('#mouse')) { return false; } 
     $('#mouse').hide(); 
     $(this).css("cursor","none"); 
     return false; 
}); 

$('#content-bg').mouseenter(function(e){ 
     if($(e.fromElement).is('#mouse')) { return false; } 
     $('#mouse').show(); 
     return false; 
}); 
+0

你沒有在你的代碼中定義了'e'它是什麼? jQuery的事件有'fromElement'屬性? – gdoron

+0

+1優雅的方式! –

+0

@gdoron:哎呀,對不起,我忘記修改時複製你的代碼。 'e'是正在傳遞給監聽者的事件。 –