Home >Web Front-end >JS Tutorial >jQuery implements simple DIV drag effect_jquery

jQuery implements simple DIV drag effect_jquery

WBOY
WBOYOriginal
2016-05-16 15:14:431149browse

The example in this article describes how to implement a simple DIV drag effect with jQuery. Share it with everyone for your reference, the details are as follows:

Create an HTML file, copy the following code into it, modify the jquery file (if you don’t have it, go to the Internet for the next one, I use jquery-1.8.2), and you can run it

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>Jquery:鼠标拖动DIV</title>
<style type="text/css">
  div#computerMove{
    position:absolute;
    top:50px;
    left:50px;
    width:200px;
    height:30px;
    line-height:30px;
    background-color:#00CCCC;
    text-align:center;
    color:#FFFFFF;
    cursor:default;
  }
</style>
</head>
<body>
  <div id="computerMove">点击我拖动</div>
  <script src="jquery-1.8.2.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(document).ready(function(){
      var $div = $("div#computerMove");
      /* 绑定鼠标左键按住事件 */
      $div.bind("mousedown",function(event){
        /* 获取需要拖动节点的坐标 */
        var offset_x = $(this)[0].offsetLeft;//x坐标
        var offset_y = $(this)[0].offsetTop;//y坐标
        /* 获取当前鼠标的坐标 */
        var mouse_x = event.pageX;
        var mouse_y = event.pageY;
        /* 绑定拖动事件 */
        /* 由于拖动时,可能鼠标会移出元素,所以应该使用全局(document)元素 */
        $(document).bind("mousemove",function(ev){
          /* 计算鼠标移动了的位置 */
          var _x = ev.pageX - mouse_x;
          var _y = ev.pageY - mouse_y;
          /* 设置移动后的元素坐标 */
          var now_x = (offset_x + _x ) + "px";
          var now_y = (offset_y + _y ) + "px";
          /* 改变目标元素的位置 */
          $div.css({
            top:now_y,
            left:now_x
          });
        });
      });
      /* 当鼠标左键松开,接触事件绑定 */
      $(document).bind("mouseup",function(){
        $(this).unbind("mousemove");
      });
    })
  </script>
</body>
</html>

Readers who are interested in more jQuery-related content can check out the special topics on this site: "JQuery drag effects and skills summary", "jQuery extension skills summary", "Summary of common classic special effects of jQuery" and "Summary of jQuery animation and special effects usage"

I hope this article will be helpful to everyone in jQuery programming.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn