简体   繁体   English

使用javascript拖放警报

[英]Alert with drag and drop using javascript

I'm still new to all this and I've been looking online but still can't figure out a way. 我对这一切仍然陌生,我一直在网上寻找,但仍然找不到解决方法。

I have a drag and drop feature. 我有拖放功能。 The user will be given an article title and is instructed to drag the article title to a box labeled 'True' or 'False'. 将为用户提供文章标题,并指示用户将文章标题拖到标有“ True”或“ False”的框。

How can I get it to alert the user when they drop it in the 'False' box? 当用户将其放在“假”框中时,如何获取警报?

Tyia!! Tyia!

HTML code: HTML代码:

<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div class="droptarget">True or False?
<div draggable="true" id="dragtarget" class="drag">Article (Drag Me!)</div>
</div>
<div class="droptarget">False</div>
<div class="droptarget">True</div>
<script src="site.js"></script>
</body>
</html>

JavaScript code: JavaScript代码:

/* Event fired on the drag target */
document.addEventListener("dragstart", function(event) {
event.dataTransfer.setData("Text", event.target.id)
//document.getElementById("demo").innerHTML = "Started to drag the p 
element."
})

/* Events fired on the drop target */
document.addEventListener("dragover", function(event) {
event.preventDefault()
})

document.addEventListener("drop", function(event) {
event.preventDefault()
var data = event.dataTransfer.getData("Text")
event.target.appendChild(document.getElementById(data))

//document.getElementById("demo").innerHTML = "The p element was 
dropped"
})

You can get the target element on the drop event handler, via event.target . 您可以通过event.targetdrop事件处理程序上获取target元素。 You also need to have a way to know it's the right element, by adding an id , a unique class , etc. 您还需要通过添加id ,唯一class等方式来了解它是正确的元素。

Example: 例:

<div class="droptarget" id="targetFalse">False</div>

And on the JS: 在JS上:

document.addEventListener("drop", function(event) {
    event.preventDefault()
    if(event.target.id==='targetFalse'){
        alert('False')
    }
...
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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