跟随鼠标移动
一、position 的四个值:static、relative、absolute、fixed。
绝对定位:absolute 和 fixed 统称为绝对定位
相对定位:relative
默认值:static
absolute:元素会脱离文档流,如果设置偏移量,会影响其他元素的位置定位
只给第五个box设置absolute:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>086事件练习</title>
<style>
*{margin: 0px;padding: 0px;}
#div1{width: 208px;height: 208px;background:url(girl.gif) no-repeat;position: absolute;}
body{background-color: black;}
</style>
<script>
window.onload=function(){
var odiv=document.getElementById("div1");
document.onmousemove=function(ev){
var e=ev||window.event;
odiv.style.left=e.clientX-75+'px';
odiv.style.top=e.clientY-75+'px';
}
}
</script>
</head>
<body>
<div id="div1"></div>
</body>
</html>
跟随鼠标一串的效果
offset() 方法设置或返回被选元素相对于文档的偏移坐标。
当用于返回偏移时:
该方法返回第一个匹配元素的偏移坐标。它返回一个带有两个属性(以像素为单位的 top 和 left 位置)的对象。
当用于设置偏移时:
该方法设置所有匹配元素的偏移坐标。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
*{margin: 0px;padding: 0px;}
div{position: absolute;width: 20px;height: 20px;background-color: red;border-radius:50%;}
</style>
<script>
window.onload=function(){
var arr=document.getElementsByTagName("div");
document.onmousemove=function(ev){
var e=ev||window.event;
for(var i=arr.length-1;i>0;i--){
arr[i].style.left=arr[i-1].offsetLeft+'px';
arr[i].style.top=arr[i-1].offsetTop+'px';
}
arr[0].style.left=e.clientX+"px";
arr[0].style.top=e.clientY+"px";
}
}
</script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>