从文本制作纯JavaScript对象以进行拖放

时间:2018-11-08 15:03:10

标签: javascript drag-and-drop

我有一个针对孩子的Java拖放测验

例如,他们可能必须用“ sat”“ on”“ the”“ chair”“ John”的五幅图像来做一个句子

问题在于所有这些图像都必须专门创建。

纯JavaScript是否有办法获取文本“ sat”并使之成为可用于拖放而不是图像的对象?

当前代码(仅包含字母拼写单词的图像)为:

function addDivs(mdiv,numA,preD,isOn){
    var tdiv = document.getElementById(mdiv);
    for(var i=0; i<numA.length;i++){
        var sLet = String(numA[i]);
        var turl = String("img/"+sLet+".gif");
        var sdiv = document.createElement("div");
        sdiv.style.width = "80px";
        sdiv.style.height = "80px";
        sdiv.id = String(preD+sLet);
        sdiv.style.margin = "5px";
        sdiv.style.display = "inline-block";
        if(isOn){
            sdiv.style.backgroundImage="url("+turl+")";
            sdiv.style.backgroundRepeat = "no-repeat";
            sdiv.addEventListener('dragstart',drag);
            sdiv.draggable = true;
        }else{
            sdiv.style.background = "white";
            sdiv.addEventListener('drop',drop);
            sdiv.addEventListener('dragover',allowDrop);
        }

        tdiv.appendChild(sdiv);
    }
}

1 个答案:

答案 0 :(得分:0)

如果有人有相同的问题,替换字母图像的方式(由程序员给我)很简单

//Replace the following lines of code in the above question

sdiv.style.backgroundImage="url("+turl+")";
sdiv.style.backgroundRepeat = "no-repeat";

// with the following two lines

sdiv.className ='stpder';
sdiv.textContent = sLet;

//define the following in the CSS

.stpder{
    background-color: white !important;
    font-size: 68px;
    line-height: 80px;
    text-align: center;
    border: solid 1px;
}