初学drag,在使用dragstart时,源元素img的src属性值获取不到是怎么回事?

初学drag,在使用dragstart时,源元素img的src属性值获取不到是怎么回事?src属性的值为undefined,麻烦各位大神看一下:

<!doctype HTML>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <meta name="description" content="">
        <meta name="keywords" content="">
        <style type="text/css">
        html,body{
            padding:0;
            margin:0;
        }
        body{
            font-family:\5b8b\4f53;
        }
        img{
            border:0;
            vertical-align:top;
        }
        .clear{
            zoom:1;
        }
        .clear:after{
            display:block;
            clear:both;
            content:"";
        }
        #example1{
            width:1000px;
            margin:0 auto;
            background:#eee;
        }
        #source,#target{
            width:180px;
            height:126px;
            background:#ddd;
        }
        #source{
            float:left;
        }
        #target{
            float:right;
            text-align:center;
            line-height:128px;
            font-size:40px;
            text-shadow:2px 2px 2px #666;
        }
        </style>
        <script type="text/javascript">
        window.onload=function(){
            tool.drag();
        }

        var tool={};

        tool.drag=function(){
            var dragEle=document.getElementById("source");
            var tar=document.getElementById("target");

            dragEle.addEventListener("dragstart",start);
            tar.addEventListener("dragover",move);
            tar.addEventListener("drop",finish);

            function start(){
                var e=window.event || arguments[0];
                var mySrc=dragEle.src;//获取不到src属性值,
                var transfer=e.dataTransfer;
                transfer.setData("img",mySrc);
            };

            function move(){
                var e=window.event || arguments[0];
                e.preventDefault();

            };

            function finish(){
                var e=window.event || arguments[0];
                var transfer=e.dataTransfer;
                var myTarget=transfer.getData("img");
                tar.innerHTML="<img src='"+myTarget+"' alt='' title='' width='180' />";
                transfer.clearData("img");
            }
        }
        </script>
    </head>

    <body>
        <div id="example1" class="clear">
            <div id="source"><img src="1.jpg" alt="" title="" width="180" /></div>
            <div id="target">欢迎</div>
        </div>
    </body>
</html>

1个回答

你获取的是div的标签元素啊,你应该获取img标签才对啊,在img标签上加个id

<img id="imgEle" src="1.jpg" alt="" title="" width="180" />

var imgTag = document.getElementById("imgEle");
var imgSrc = imgTag.src;
alert(imgSrc);//这里就获取到了img  的src值


Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问