<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE>rect sample</TITLE>
<script Language="javascript">
var startX,startY,endX,endY;
var dragFlag;function doMouseDown(){
dragFlag = 0;
startX = event.clientX;
startY = event.clientY;
document.all.rect.style.pixelLeft = startX;
document.all.rect.style.pixelTop = startY;
document.all.rect.style.pixelHeight = 0;
document.all.rect.style.pixelWidth = 0;
}function doMouseUp(){
dragFlag = 1;
}function doMouseMove(){
if(dragFlag == 0){
endX = event.clientX;
endY = event.clientY;
nowHeight = endY - startY;
nowWidth = endX - startX;

if(nowHeight<0){
document.all.rect.style.pixelTop = endY;
nowHeight = -1*nowHeight;
}
if(nowWidth<0){
document.all.rect.style.pixelLeft = endX;
nowWidth = -1*nowWidth;
} document.all.rect.style.pixelHeight = nowHeight;
document.all.rect.style.pixelWidth = nowWidth;
}
}document.onmousemove = doMouseMove;
document.onmousedown = doMouseDown;
document.onmouseup = doMouseUp;</script>
<div id="rect" style="position:absolute;left:0px; top:0px;width:0;height:0;border-top: 1px dotted #999999;border-left: 1px dotted #999999;border-right: 1px dotted #999999;border-bottom: 1px dotted #999999;">
</div>
</HEAD><BODY>
</BODY>
</HTML>
注:以上代码只是雏形,实现了拖动矩形的功能,你可以根据自己的需要进行改动。

解决方案 »

  1.   

    <html xmlns:v="urn:schemas-microsoft-com:vml">
    <head>
    <STYLE>
    v\:* { Behavior: url(#default#VML) }
    </STYLE>
    <script language="JavaScript">
    <!--
    var x=0;
    var y=0;
    var isMouseDown=false;
    var newRect=null;document.onmousedown=function(){
    x=window.event.clientX;
    y=window.event.clientY;
    isMouseDown=true;
    if(newRect==null)
    newRect=document.createElement('<v:rect filled="false" colors="30% yellow,70% green" style="position:absolute; top:'+ y +';left:'+ x +';width:1px;height:1px"></v:rect>');
    else{
    newRect.style.top=y;
    newRect.style.left=x;
    newRect.style.width="1px";
    newRect.style.height="1px";
    }
    newRect.style.border="2px solid blue";//这里设置border的样式
    }
    document.onmousemove=function(){
    if(isMouseDown==false) return;
    document.body.insertBefore(newRect);
    var mx=window.event.clientX;
    var my=window.event.clientY;
    if(mx>x){
    newRect.style.width=mx-x;
    }
    else{
    newRect.style.width=x-mx;
    newRect.style.left=mx;
    }
    if(my>y){
    newRect.style.height=my-y;
    }
    else{
    newRect.style.height=y-my;
    newRect.style.top=my;
    }}
    document.onmouseup=function(){
    x=0;
    y=0;
    isMouseDown=false;
    }//-->
    </script>
    </head>
    <body onselectstart="return false;"></body>
    </html>