2016-02-04 189 views
1

我有以下jQuery和JS代碼:page.Y返回錯誤的值

$(function() { 
    function addMouseEvents() { 
    $('img').addClass('close-overlay-active') 
    var close_H = ($('.close-overlay-active').height() * 1.2); 
    var close_W = ($('.close-overlay-active').width() * 1.2); 
    document.addEventListener('mousemove', function(e) { 
     // console.log('move'); 
     // console.log(e.pageX + " " + e.pageY); 
     var mouseX = e.pageX, 
     mouseY = e.pageY; 

     $('.close-overlay-active') 
     .css({ 
      top: (mouseY - close_H), 
      left: mouseX - close_W 
     }); 
    }); 
    } 


    addMouseEvents(); 
}); 

的期望的行爲ofcourse爲的「x」標記是略微光標上方。這確實發生在大多數情況下,但有時「x」出現在光標右下方的光標下方,有時在光標下方出現1000px。這是爲什麼發生? e.pageY似乎有時會返回錯誤的值爲什麼?

有人可以請解釋這種行爲嗎?

FIDDLE HERE

+0

這一切的權利https://開頭的jsfiddle .net/rayon_1990/r25o2Lmr/3 /? – Rayon

+0

對我來說工作正常 – Siddharth

回答

1

試試這個:

$(function() { 
 
    function addMouseEvents() { 
 
    $('img').addClass('close-overlay-active') 
 
    var close_H = ($('.close-overlay-active').height()); 
 
    var close_W = ($('.close-overlay-active').width()); 
 
    document.addEventListener('mousemove', function(e) { 
 
     // console.log('move'); 
 
     // console.log(e.pageX + " " + e.pageY); \t 
 
     var mouseX = e.pageX, 
 
     mouseY = e.pageY; 
 

 
     $('.close-overlay-active') 
 
     .css({ 
 
      top: (mouseY - close_H), 
 
      left: mouseX - close_W/2 
 
     }); 
 
    }); 
 
    } 
 

 

 
    addMouseEvents(); 
 
});
img { 
 
    position: absolute; 
 
    top: 0; 
 
    left: 0; 
 
} 
 
.fixed { 
 
    position: fixed; 
 
    top: 0; 
 
    left: 0; 
 
    right: 0; 
 
    bottom: 0; 
 
    background: #b0e2ff; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> 
 
<div class="fixed"> 
 
    <img src="https://cdn3.iconfinder.com/data/icons/sympletts-free-sampler/128/circle-close-128.png"> 
 
</div>

要獲得準確的光標在該中心,請參閱本FIDDLE

+0

'mouseY'不會給我正確的價值! ..我沒有問題'mouseX' –

+0

你在執行上面的代碼時遇到了什麼問題? – Rayon