简体   繁体   中英

drag and drop isn't functioning?

I'm a beginner at Javascript and I'm trying to get the image to go inside the border that is made with css and for some reason the script isn't functioning it might be that i had a small mistake in the code or something else.

The snippet works fine but it doesn't show the image.

"e" is short for event i have a: drag(e) allowdrop(e) and drop(e)
Thanks

 <!doctype html> <html> <head> <title>drag and drop</title> <style type="text/css"> #targetDiv { margin-left: 300px; width: 200px; height: 150px; padding: 10px; border: 1px solid #999999; } </style> </head> <body> <h1>drag and drop</h1> <div id="targetDiv" ondragover="allowDrop(event)" ondrop="drop(event)"></div> <img id="dragItem" src="market-street-car.jpg" width="200" height="150" draggable="true" ondragstart="drag(event)" /> <script> function drag(e) { e.dataTransfer.setData("Text", e.target.id); } function allowDrop(e) { e.preventDefault(); } function drop(e) { var dragItem = e.dataTransfer.getData("Text"); e.preventDefault(); e.target.appendChild(document.getElementById(dragItem)); } //You don't need to edit this one cuz you don't need var var is probably optional </script> </body> </html> 

Here is corrected version. You have missed an ) character, and I've added one var expression exactly here: take.ms/el76e

 <!doctype html> <html> <head> <title>drag and drop</title> <style type="text/css"> #targetDiv { margin-left: 300px; width: 200px; height: 150px; padding: 10px; border: 1px solid #999999; } </style> </head> <body> <h1>drag and drop</h1> <div id="targetDiv" ondragover="allowDrop(event)" ondrop="drop(event)"></div> <img id="dragItem" src="market-street-car.jpg" width="200" height="150" draggable="true" ondragstart="drag(event)" /> <script> function drag(e) { e.dataTransfer.setData("Text", e.target.id); } function allowDrop(e) { e.preventDefault(); } function drop(e) { e.preventDefault(); var dragItem = e.dataTransfer.getData("Text"); e.target.appendChild(document.getElementById(dragItem)); } </script> </body> </html> 

It looks like the code isn't working with the image, since all I can get from running the code snippet is the result of the "allowDrop" function. An error like the one on your dragItem could cause this:

ragstart="drag(event"   

Is missing the closing ")"

One thing I always do when debugging Javascript is open the Js console (ctrl+shift+j) and monitor it as I go through the page, an error could appear briefly that you wouldn't otherwise find just running the page itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM