<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Document</title> <style> #box{ width:300px; height:180px; border:1px solid #000; } #img1{ width:200px; height:120px; margin: 20px; } </style> </head> <body> <div id="box"></div> <img src="img/6.jpg" id="img1" draggable="true"> <script> window.onload=function(){ var box=document.getElementById('box'), img1=document.getElementById('img1'); img1.ondragstart=drag(event); box.ondragover=allowdrop(event); box.ondrop=drop(event); function allowdrop(ev){ ev.preventDefault(); } function drag(ev){ ev.dataTransfer.setData("Text",ev.target.id); } function drop(ev){ ev.preventDefault(); var data=ev.dataTransfer.getData("Text"); ev.target.appendChild(document.getElementById(data)); } } </script> </body> </html>
当我把ondragstart ondragover ondrop事件放在HTML元素标签内时,代码正常运行,但是像上边放在<script>中时,就会出现错误Uncaught TypeError: Cannot read property 'setData' of undefined 请问各位大神是哪里出了问题,怎么修改?