65.9K
CodeProject 正在变化。 阅读更多。
Home

拖动和移动项目

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.83/5 (3投票s)

2008 年 7 月 30 日

CPOL
viewsIcon

25831

downloadIcon

251

您可以通过鼠标拖动和移动页面上的项目

引言

  1. 在你的项目的样式中(例如 img, div 等),将定位设置为绝对定位,例如
    <div style="position:absolute" id="move_id" onmousedown="mousedown()" onmouseup="mouseup()">
  2. 你应该有一个临时变量来描述项目状态。将显示设置为 none 来隐藏这个临时变量。这个输入框的值描述了状态。值 0 表示项目没有被拖动。当你的鼠标按下项目时 (onmousedown),这个值将被设置为 1,准备好进行拖动和移动。
    <input type="text" style="display:none" id="temp_id" value="0"> 
  3. <body> 设置成这样
    <body onmousemove="mousemove();">
  4. 现在我们可以创建 JavaScript 函数了
    <script language="javascript" type="text/javascript">
    function mousedown()
    {
        document.getElementById("temp_id").value = "1";
        
    }
    function mouseup()
    {
        document.getElementById("temp_id").value = "0";
        document.getElementById("move_id").style.cursor = "default";
    }
    function mousemove()
    {
        if (document.getElementById("temp_id").value == "1")
        {
            document.getElementById("move_id").style.top = event.clientY - 10;
            document.getElementById("move_id").style.left = event.clientX - 50;
            document.getElementById("move_id").style.cursor = "move";
        }
    }
    </script>
© . All rights reserved.