Jquery div跟随鼠标效果实现
2011-03-14 阅读 150
在多种浏览器(ie、firefox、chrome,甚至safai)中,实现统一div跟随鼠标效果,并非想象的那么复杂。
HTML代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jquery鼠标跟随效果</title>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<div id="wrap" style="position:relative; width:960px; float:right;">
<div style="position:absolute; top:0; left:0;">
<div class="mainbox"></div>
<div class="mainbox"></div>
<div class="mainbox"></div>
<div class="mainbox"></div>
<div class="mainbox"></div>
</div>
<div style="position:absolute; bottom:0; left:0;">
<div class="mainbox"></div>
<div class="mainbox"></div>
<div class="mainbox"></div>
<div class="mainbox"></div>
<div class="mainbox"></div>
</div>
<div style="position:absolute; top:50%; left:0; margin-top:-75px;">
<div class="mainbox"></div>
<div class="mainbox"></div>
<div class="mainbox"></div>
<div class="mainbox"></div>
<div class="mainbox"></div>
</div>
</div>
<div style="clear:both"></div>
<br />
<br />
<br />
<br />
<br />
<p id="float">数据读取中...<br />数据读取中...<br />数据读取中...<br />数据读取中...<br />数据读取中...<br />数据读取中...<br />数据读取中...<br />数据读取中...<br />数据读取中...<br />数据读取中...<br />数据读取中...<br />数据读取中...<br /></p>
</body>
</html>
```
CSS代码:
* {
margin:0;
padding:0;
border:0;
}
.mainbox {
width:150px;
height:150px;
background:#333;
float:left;
margin-right:30px;
}
#float {
border:1px solid #333;
background:#999;
padding:10px;
position:absolute;
left:0;
top:0;
z-index:9999;
display:none;
}
```
Javascript代码:
<script type="text/javascript">
var floatX,floatY,boxX,boxY,pageX,pageY; //定义六个变量。
var cX = document.documentElement.clientWidth; //网页可见区域宽
var cY = document.documentElement.clientHeight; //网页可见区域高
$(document).ready(function(){
$('#wrap').css({height:cY}); //给Id为wrap的元素添加高度
//从这里开始
$('.mainbox').hover(function(){ //给class为mainbox的元素添加鼠标滑动效果。
$(this).mousemove(function(event){
pageX = event.clientX + $(window).scrollLeft(); //clientX 事件属性返回当事件被触发时鼠标指针向对于浏览器页面(或客户区)的水平坐标。
pageY = event.clientY + $(window).scrollTop(); //clientY 事件属性返回当事件被触发时鼠标指针向对于浏览器页面(或客户区)的垂直坐标。
boxX = $('#float').outerWidth(true); //获取第一个匹配元素外部宽度(默认包括补白和边框)
boxY = $('#float').outerHeight(true); //获取第一个匹配元素外部高度(默认包括补白和边框)
if ((cX - event.clientX) < (boxX + 35)){
floatX = pageX - boxX - 15;
}else{
floatX = pageX + 15;
}
if ((cY - event.clientY) < (boxY + 10)){
floatY = pageY - boxY - 10;
}else{
floatY = pageY + 10;
}
$('#float').css({top: floatY, left: floatX});
$('#float').show();
});
},function(){
$('#float').hide();
})
$(window).resize(function() { //当窗口改变大小时触发的函数
cX = document.documentElement.clientWidth;
cY = document.documentElement.clientHeight;
});
})
```
jquery div 跟随 鼠标 效果 实现 ie firefox chrome safari
更新于 2023年03月28日