前端----HTML5实现图片拖放

HTML5新增了关于拖放的API,通过拖放API可以让HTML界面的任意元素都变成可拖动的,通过使用拖放机制可以开发出更友好的人机交互界面.

1.在HTML5中,<img.../>元素默认是可拖动的;而<a.../>元素只要设置了href属性,它默认也是可拖动的.

如下面代码所示:


<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    <title>可拖动</title>
</head>
<body>
<a herf="http://www.fkjava.org">疯狂软件教育</a>
<img src="images/logo1.jpg" alt="crazyit"/>
</body>
</html>

 2.实现图片接受释放后的放,应给document的ondragover事件指定监听器.

如下面代码所示:


<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    <title>可拖动Div</title>
</head>
<body>
<div id="source" style="width:80px;height:80px;
     border:1px solid black;
     background-color:#bbb;"
     draggable="true">疯狂软件教育</div>
  <script type="text/javascript">
    var source=document.getElementById("source");
    source.ondragstart=function(evt)
{
      evt.dataTransfer.setData("text","www.fkjava.rog");
}
    document.ondragover=function(evt)
{
      return false;
}
    document.ondrop=function(evt)
{
source.style.position="absolute";
source.style.left=evt.pageX+"px";
source.style.top=evt.pageY+"px";
return false;
}
</script>
</body>
</html>

在上面的代码中<head...><head.../> 中定义这段代码相关属性,在body中先设置了一个80*80的div,将id设为source,为了让下面js代码中方法识别出该div.在<script...>和<script.../>中先用var定义了一个source对象获取div,然后执行以次下面三个方法实现图片可拖动的行为.

猜你喜欢

转载自blog.csdn.net/weixin_42504145/article/details/82813085