javascript 简单实现页面上的拖放功能

<html>

<head>
<style type="text/css">
td{text-align:center}
th{text-decoration: underline}
.blanks{text-decoration:underline}
</style>
<title></title>
<script type="text/javascript">
var timer;
function setupDrag()
{
    if(event.srcElement.tagName != "TD")
    {
        event.returnValue = false;
    }
    else
    {
        var passedData = [event.srcElement.innerText, event.srcElement.className];
        event.dataTransfer.setData("Text",passedData.join(":"));
        event.dataTransfer.effectAllowed= "copy";
        timer = new Date();
    }
}

function timeIt()
{
    if(event.srcElement.tagName == "TD"&&timer)
    {
        if((new Date())-timer>6000)
        {
            alert("Sorry, time is up,Try again.")
            timer = 0;
        }
    }
}

function handleDrop()
{
    var elem = event.srcElement;
    var passedData = event.dataTransfer.getData("Text");
    var errMsg = "";
    if(passedData)
    {
        passedData =  passedData.split(":");
        if(elem.id=="blank1")
        {
            if(passedData[1] =="noun")
            {
                event.dataTransfer.dropEffect ="copy";
                event.srcElement.innerText = passedData[0];
            }
            else
            {
                errMsg = "You cannot put an adjective into the noun placeholder.";
            }
        }
        else if(elem.id=="blank2")
        {
            if(passedData[1] =="adjective")
            {
                event.dataTransfer.dropEffect = "copy";
                event.srcElement.innerText = passedData[0];
            }
            else
            {
                errMsg = "You cannot put an noun into the noun placeholder.";
            }
        }
        if(errMsg)
        {
            alert(errMsg);
        }
    }
}

function cancelDefault()
{
    if(event.srcElement.id.indexOf("blank")==0)
    {
        event.dataTransfer.dropEffect = "copy";
        event.returnValue = false;
    }
}
</script>

</head>

<body ondragstart="setupDrag()" ondblclick="timeIt()">
<center>
<table border="2" cellpadding="5">
   <tr>
      <th>Nouns</th>
      <th>Adjective</th>
   </tr>
   <tr>
      <td class="noun">truck</td>
      <td class="adjective">round</td>
   </tr>
   <tr>
      <td class="noun">doll</td>
      <td class="adjective">red</td>
   </tr>
   <tr>
      <td class="noun">ball</td>
      <td class="adjective">Pretty</td>
   </tr>
</table>
<p id="myP" ondragenter="cancelDefault()" ondragover="cancelDefault()" ondrop="handleDrop()">Pat said,"oh my, the<span id="blank1" class="blanks">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</span>is so <span id="blank2" class="blanks">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;</span>!"</p>
<button onclick="location.reload()">Reset</button>
</center>
</body>

</html>

posted @ 2008-05-26 15:16  Amanda2007  阅读(290)  评论(0编辑  收藏  举报