当前位置: 移动技术网 > IT编程>开发语言>JavaScript > jquery div拖动效果示例代码

jquery div拖动效果示例代码

2019年03月19日  | 移动技术网IT编程  | 我要评论

代码如下:


<%@ page language="java" contenttype="text/html; charset=utf-8"
pageencoding="utf-8"%>
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "https://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>拖动div</title>
<style type="text/css">
.show{
background:#7cd2f8;
width:100px;
height:100px;
text-align:center;
position:absolute;
z-index:1;
left:100px;
top:100px;
}

</style>
<script type="text/javascript" src="../script/jquery-1.7.2.js"></script>
<script type="text/javascript"><!--
$(document).ready(function()
{
$(".show").mousedown(function(e)//e鼠标事件
{
$(this).css("cursor","move");//改变鼠标指针的形状

var offset = $(this).offset();//div在页面的位置
var x = e.pagex - offset.left;//获得鼠标指针离div元素左边界的距离
var y = e.pagey - offset.top;//获得鼠标指针离div元素上边界的距离
$(document).bind("mousemove",function(ev)//绑定鼠标的移动事件,因为光标在div元素外面也要有效果,所以要用doucment的事件,而不用div元素的事件
{
$(".show").stop();//加上这个之后

var _x = ev.pagex - x;//获得x轴方向移动的值
var _y = ev.pagey - y;//获得y轴方向移动的值

$(".show").animate({left:_x+"px",top:_y+"px"},10);
});

});

$(document).mouseup(function()
{
$(".show").css("cursor","default");
$(this).unbind("mousemove");
})
})

// --></script>
</head>
<body>
<p class="show">
jquery实现div层拖动
</p>
</body>
</html>

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网