单击以下代码中的圆角矩形之一时,需要创建 span 元素的副本并将其放置在原始元素的顶部。代码会这样做,但新元素的高度增加了。请提出可能出错的地方。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
<div id="phrasesDiv" style="line-height:250%" /></div>
<style type="text/css">
.phrase {
font-size:18pt;
color:blue;
background: palegreen;
border:2px solid green;
padding:2px 10px 2px 10px;
-webkit-border-radius:10px;
}
</style>
<script type="text/javascript">
{
// create the phrase list dynamically
var phraseList = "Apple~Orange~Kiwi~Guava";
var phrasesDiv = document.getElementById("phrasesDiv");
var phrases = phraseList.split('~');
for (var i=0; i<phrases.length; i++)
phrasesDiv.innerHTML += "<span id=\""+phrases[i]+"\" class=\"phrase\" onmousedown=\"phraseTouched('"+phrases[i]+"')\">"+phrases[i]+"</span> \n";
}
function getDim(el) {
var lw = el.offsetWidth;
var lh = el.offsetHeight;
for (var lx=0, ly=0; el != null; lx += el.offsetLeft, ly += el.offsetTop, el = el.offsetParent);
return {x:lx,y:ly,w:lw,h:lh};
}
function phraseTouched(id) {
var elem = document.getElementById(id);
var dim = getDim(elem);
var dragElem = document.createElement('span')
dragElem.id = id+"_copy";
dragElem.innerHTML = id;
dragElem.className += " phrase";
dragElem.style.background = "pink";
dragElem.style.position = "absolute";
dragElem.style.left = dim.x+"px";
dragElem.style.top = dim.y+"px";
elem.parentNode.appendChild(dragElem);
}
</script>
</html>
编辑:以下功能有效......但我仍然很想知道如果我以编程方式添加到 div 会增加高度。
function phraseTouched(id) {
var elem = document.getElementById(id);
var dim = getDim(elem);
document.body.innerHTML += "<span id=\"_"+id+"\" class=\"phraseDrag\" style=\"left:"+dim.x+"px;top:"+dim.y+"px;position:absolute;\">"+id+" </span>\n";
}