我正在尝试将图像放置在由javascript函数生成的div标签内。问题是图像的位置不是从左边75像素,从顶部40像素,而是停留在0,0。这是代码。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<HTML lang="en">
<HEAD>
<META http-equiv="Content-Type" content="text/html">
</HEAD>
<SCRIPT language = "JavaScript">
var my_div = null;
var newDiv = null;
function creatediv(id, width, height, left, top, opacity)
{
var newdiv = document.createElement('div');
newdiv.setAttribute('id', id);
newdiv.style.width = width + "px";
newdiv.style.height = height + "px";
newdiv.style.position = "absolute";
newdiv.style.left = left + "px";
newdiv.style.top = top + "px";
newdiv.style.opacity = opacity;
document.body.appendChild(newdiv);
my_div = document.getElementById(id);
document.body.insertBefore(newdiv, my_div);
}
</SCRIPT>
<BODY onload=" creatediv('logo', 792, 1000, 75, 40, 1)">
<div id = "logo" style=" z-index:1; font-size:200%; ">
<img src="some.gif" width="10%" height="10%">
</div>
</BODY>
</html>
最佳答案
试试这个:Live Demo
function updateDiv(id, width, height, left, top, opacity)
{
var mydiv = document.getElementById(id);
mydiv.setAttribute('id', id);
mydiv.style.width = width + "px";
mydiv.style.height = height + "px";
mydiv.style.position = "absolute";
mydiv.style.left = left + "px";
mydiv.style.top = top + "px";
mydiv.style.opacity = opacity;
}
输出量
<body onload=" updateDiv('logo', 792, 1000, 75, 40, 1)">
<div id="logo" style="z-index: 1; font-size: 200%; width: 792px; height: 1000px; position: absolute; left: 75px; top: 40px; opacity: 1;">
<img src="1.jpg" width="10%" height="10%">
</div>
</body>
更新资料
如果需要将图像文件作为参数传递:
的HTML
<BODY onload=" updateDiv('logo', 792, 1000, 75, 40, 1, '1.jpg')">
<div id = "logo" style=" z-index:1; font-size:200%; "></div>
</BODY>
Java脚本
function updateDiv(id, width, height, left, top, opacity, imgSrc)
{
var mydiv = document.getElementById(id);
mydiv.setAttribute('id', id);
mydiv.style.width = width + "px";
mydiv.style.height = height + "px";
mydiv.style.position = "absolute";
mydiv.style.left = left + "px";
mydiv.style.top = top + "px";
mydiv.style.opacity = opacity;
mydiv.innerHTML = '<img src="' + imgSrc + '" width="10%" height="10%">';
}