<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#container {
width: 800px;
height: 600px;
position: absolute;
top:10px;
left: 150px;
background: gray;
}
#box {
width: 100px;
height: 100px;
background: red;
position: absolute;
top:20px;
left:100px;
cursor: default;
/*display: none;*/
}
</style>
</head>
<body>
<div id="container">
<div id="box"></div>
</div>
<script type="text/javascript" src="js/tools.js"></script>
<script type="text/javascript">
/*$("#container").onmouseover = function(){
$("#box").style.display = "block";
}
$("#container").onmouseout = function(){
$("#box").style.display = "none";
}*/
var containerWidth = $("#container").clientWidth,
containerHeight = $("#container").clientHeight,
boxWidth = $("#box").clientWidth,
boxHeight = $("#box").clientHeight;
document.onmousemove = function(e){
e = e || event;
// 将小盒子在文档中定位到光标处
offset($("#box"), {top:e.pageY - boxHeight / 2, left:e.pageX - boxWidth / 2});
// 获取小盒子相对其有定位的父盒子的绝对定位位置
var _top = $("#box").offsetTop,
_left = $("#box").offsetLeft;
if (_left < 0)
_left = 0;
else if (_left > containerWidth - boxWidth)
_left = containerWidth - boxWidth;
if (_top < 0)
_top = 0;
else if (_top > containerHeight - boxHeight)
_top = containerHeight - boxHeight;
$("#box").style.left = _left + "px";
$("#box").style.top = _top + "px";
}
</script>
</body>
</html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#container {
width: 800px;
height: 600px;
position: absolute;
top:10px;
left: 150px;
background: gray;
}
#box {
width: 100px;
height: 100px;
background: red;
position: absolute;
top:20px;
left:100px;
cursor: default;
/*display: none;*/
}
</style>
</head>
<body>
<div id="container">
<div id="box"></div>
</div>
<script type="text/javascript" src="js/tools.js"></script>
<script type="text/javascript">
/*$("#container").onmouseover = function(){
$("#box").style.display = "block";
}
$("#container").onmouseout = function(){
$("#box").style.display = "none";
}*/
var containerWidth = $("#container").clientWidth,
containerHeight = $("#container").clientHeight,
boxWidth = $("#box").clientWidth,
boxHeight = $("#box").clientHeight;
document.onmousemove = function(e){
e = e || event;
// 将小盒子在文档中定位到光标处
offset($("#box"), {top:e.pageY - boxHeight / 2, left:e.pageX - boxWidth / 2});
// 获取小盒子相对其有定位的父盒子的绝对定位位置
var _top = $("#box").offsetTop,
_left = $("#box").offsetLeft;
if (_left < 0)
_left = 0;
else if (_left > containerWidth - boxWidth)
_left = containerWidth - boxWidth;
if (_top < 0)
_top = 0;
else if (_top > containerHeight - boxHeight)
_top = containerHeight - boxHeight;
$("#box").style.left = _left + "px";
$("#box").style.top = _top + "px";
}
</script>
</body>
</html>