您不能在 SVG 中使用拖动事件,但有一个技巧。通过在其中一个部分上设置 z-index 属性,您可以拥有两个部分(一个覆盖另一个)。
看看下面的代码:
CSS:
#container{
text-align: center;
margin: -20px 20% 0 20%;
background: #b9cae5;
}
#SVGs{
width:100px;
height:100px;
margin: 20px 0 0 350px;
position:relative;
}
.sec1,.sec2{
width:100px;
height:100px;
position:absolute;
top:0;
left:0;
}
.sec1{
z-index:10;
}
在您的 HTML 中:
<section id ="container">
<section id="SVGs">
<section class="sec2">
<svg width="100" height="100">
<circle id="abc" cx="50" cy="50" r="50" stroke="black" fill="yellow">
</circle>
</svg>
</section>
<section id="sec1"class="sec1" ondrop="drop(event)" ondragover="allowDrop(event)">
</section>
<br/><br/>
</section>
<section>
<p> <strong>Drag the gif image to the SVG circles above.</strong>
</p>
<img id="drg1" alt="Check Internet Connection"src="https://media.giphy.com/media/l3vR16pONsV8cKkWk/giphy.gif" draggable="true" ondragstart="drag(event)" width="100" height="100"/>
</section>
还有你的脚本:
<script>
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>
希望对你有帮助:)