首先將一個元素定位在當前頁面的中心位置(自適應),然後用mousemove 去監聽鼠標,實時計算鼠標當前位置到元素中心的距離。
html
<html>
<head></head>
<body>
<a id='text'></a>
<div id='center_box'></div>
</body>
</html>
css
#center_box{
width:100px;
height:100px;
position:absolute;
top:0;
bottom:0;
left:0;
right:0;
margin:auto;
}
js
<script>
(function(){
/*變量解析:
txt 用來存儲計算出的距離 */
var txt,$a=$('#text');
//計算函數
function calculateDistance(moveX,moveY){
//獲取div 的中心點座標
var $divx=document.documentElement.clientWidth/2;
var $divy=document.documentElement.clientHeight/2;
//鼠標在div 右側,計算出的值是負數,所以要用abs 絕對值來轉成正數
var newx=Math.abs($divx-moveX);
var newy=Math.abs($divy-moveY);
return newx>=newy?newx:newy;
}
//現在計算函數準備好了,我們來寫最重要的一步,監聽事件
$(document).mousemove(function(event){
var e=event || window.event;
txt=calculateDistance(e.clientX,e.clientY);
$a.text=txt;
})
})()
//window 自執行函數,實時監聽,
!function(){
function divtop(){
$('#center_box').css('margin-top',(document.documentElement.clientHeight-$div[0].clientHeight)/2);
}
divtop();
}(window)
</script>