alert(getPosition(mainDiv).left); //undefined,不知道是为什么,应该怎么解决。
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style >
body{
background-color:#f8f8f8;
}
#box{
position:absolute;
top:100px;
left:200px;
width:440px;
height:269px;
}
#img1{
position:absolute;
top:0;
left:0;
opacity:0.5;
}
#img2{
position:absolute;
top:0;
left:0;
clip:rect(0px 200px 200px 0px);
}
#main{
position:absolute;
border:1px solid #fff;
width:200px;
height:200px;
}
.minDiv{
position: absolute;
width: 8px;
height: 8px;
background-color: #FFFFFF;
}
.left-up{
top: -4px;
left: -4px;
cursor: nw-resize;
}
.up{
left: 50%;
top: -4px;
margin-left: -4px;
cursor: n-resize;
}
.right-up{
top: -4px;
right:-4px ;
cursor: ne-resize;
}
.right{
top: 50%;
margin-top: -4px;
right: -4px;
cursor: e-resize;
}
.right-down{
right: -4px;
bottom: -4px;
cursor: se-resize;
}
.down{
left: 50%;
bottom: -4px;
margin-left: -4px;
cursor: s-resize;
}
.left-down{
left: -4px;
bottom: -4px;
cursor: sw-resize;
}
.left{
left: -4px;
top: 50%;
margin-top: -4px;
cursor: w-resize;
}
</style>
<script>
window.onload = function(){
var rightDiv = document.getElementById("right");
var mainDiv = document.getElementById("main");
var ifKeyDown = false;//鼠标按下状态
//鼠标按下事件
rightDiv.onmousedown = function(){
ifKeyDown = true;
}
//鼠标松开事件
window.onmouseup = function(){
ifKeyDown = false;
}
//鼠标移动事件
window.onmousemove = function(e){
if(ifKeyDown == true){
alert("aaa");
var x = e.clientX;//鼠标x坐标 401
var addWidth = "";//鼠标移动后选取框增加的宽度
var widthBefore = mainDiv.offsetWidth - 2;//选取框变化前的宽度(-去掉border的宽度)200
addWidth = x - getPosition(mainDiv).left - widthBefore ;//鼠标移动后增加的宽度
alert(getPosition(mainDiv).left); //undefined
mainDiv.style.width = addWidth + widthBefore +"px";//选取框变化后的宽度
}
}
}
//获得元素相当于屏幕左边的距离 利用offsetLeft
function getPosition(node){
var left = node.offsetLeft;
var top = node.offsetTop;
var parent = node.offsetParent;
while(parent != null){
left += parent.offsetLeft;
top +=parent.offsetTop;
parent = parent.offsetParent;
}
return {"left:":left, "top:":top};
}
</script>
</head>
<body>
<div id="box" >
<img src="back1.jpg" id="img1"/>
<img src="back1.jpg" id="img2"/>
<div id="main">
<div id="left-up" class="minDiv left-up"></div>
<div id="minDiv up" class="minDiv up"></div>
<div id="right-up" class="minDiv right-up"></div>
<div id="right" class="minDiv right" ></div>
<div id="right-down" class="minDiv right-down"></div>
<div id="down" class="minDiv down"></div>
<div id="left-down" class="minDiv left-down"></div>
<div id="left" class="minDiv left"></div>
</div>
</div>
</body>
</html>