Posted in jQuery onAugust 14, 2018
本文实例讲述了jQuery实现的简单拖拽功能。分享给大家供大家参考,具体如下:
<!doctype html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>3water.com jQuery拖拽</title> <style type="text/css"> #box{ position:fixed; left:100px; top:100px; background-color:red; width:300px; height:200px; } #out{ height:2000px; } </style> <script src="http://libs.baidu.com/jquery/2.0.3/jquery.min.js"></script> <script> $(document).ready(function(){ var drafting=false; var offX,offY,mouseX,mouseY,winX,winY,x,y; $("#box").mousedown(function(event){ event.stopPropagation(); drafting=true; }); $(document).mousemove(function(event){ event.stopPropagation(); var e=event||window.event; mouseX=e.pageX||e.clientX+$(document).scrollLeft(); mouseY=e.pageY||e.clientY+$(document).scrollTop(); winX=$("#box").offset().left-$(document).scrollLeft(); winY=$("#box").offset().top-$(document).scrollTop(); if(drafting==false){ offX=mouseX-winX; offY=mouseY-winY; } x=mouseX-offX; y=mouseY-offY; $("#box").css({'left':x,'top':y}); }); $(document).mouseup(function(event){ event.stopPropagation(); drafting=false; }); }); </script> </head> <body> <div id="box"></div> <div id="out"></div> </body> </html>
这里使用在线HTML/CSS/JavaScript代码运行工具:http://tools.3water.com/code/HtmlJsRun,可得到如下测试效果:
希望本文所述对大家jQuery程序设计有所帮助。
jQuery实现的简单拖拽功能示例【测试可用】
- Author -
筱葭声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Reply on: @reply_date@
@reply_contents@