动态添加diV,实现了拖拽功能

本文介绍了一段HTML和JavaScript代码,演示如何使用DOM操作创建可交互的div元素,并通过事件监听实现基本的拖拽功能。代码包括元素创建、样式设置以及鼠标事件响应,展示了前端开发中动态交互的实现。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
<script>
   function creatediv()
   {
        var obj = document.createElement("div");
  classA.call(obj);  
  bd.appendChild(obj);
   }
 
 function classA(){
   
  this.style.width="100";
  this.style.height="100";
  this.style.background="blue";
  this.style.border="solid 10 red ";
  //this.style.display="inline";
  this.style.position="absolute";   //relative
  //   this.style.left=50;
  //   this.style.top=50;
  this.onmousedown=function()
                   {down(this)};
  this.onmousemove=function()
                   {move(this)};
  this.onmouseup=function()
                    {up(this)};

  
 }
 
 var flag=0;
 function down(aa){
  flag=1;
 }
 function move(aa)
 {
     if(flag==1)
  {
         aa.style.left=event.x-50;
   aa.style.top=event.y-50;
   }
 }
 function up(aa){
  flag=0;
 }
</script>
</HEAD>

<BODY id="bd" >
<input type ="button"  onclick="creatediv();"  value="创建" /> 
</BODY>
</HTML>

down()  ,move()  ,up() 这3个函数是实现拖拽功能的!其实你可以不要它。

 

call方法是一个回调方法,每点击一下call就回调classA()这个函数一次。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值