【问题标题】:HTML 5 SVG With Drag and Drop具有拖放功能的 HTML 5 SVG
【发布时间】:2018-09-19 12:58:59
【问题描述】:

我想将图像拖入 SVG 圆圈。虽然调试图像可以作为一个孩子使用,但它没有显示在圆圈上。当我将相同的图像拖到 <div> 元素中时,它工作正常,但不适用于 <SVG><Image> 标签。使用<div> 可以正常工作,但使用<IMAGE> 则不行。

问。使用 SVG 绘制一个黄色和绿色的圆圈,并允许用户将徽标拖放到圆圈中。

https://www.w3schools.com/code/tryit.asp?filename=FVF69MCUNTQ0

【问题讨论】:

标签: html


【解决方案1】:

您不能在 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>

希望对你有帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-12
    • 2021-06-11
    • 2013-08-15
    • 1970-01-01
    相关资源
    最近更新 更多