动态创建的DIV在其他创建按钮中的位置

Position of Dynamically Created DIV within other Created Buttons

本文关键字:创建 位置 按钮 DIV 动态 其他      更新时间:2023-09-26

我有一个div正在用Javascript创建,幻灯片正在进行中。一切都很好,执行这个DIV的定位。我希望它在页面的后面,但无论我把创建它的document.write放在哪里,DIV在Firefox中都保持在顶部;铬。对于IE,它不会显示,除非代码在我的脚本顶部。有什么建议或解决方案吗?

writeButton("","/page1.html","light_box_b01",206,298,"","",0);
writeButton("","/page2.html","light_box_b02b",206,84,"","",0);
document.write('<div id="fadeshow1" style="margin-top:5px; margin-bottom:5px;"></div>')
writeButton("","/page3.html","light_box_b03b",206,89,"","",0);
writeButton("","/page4.html","closeout",206,78,"","",0);
document.write("<td><img src='""+loc+"Separator02"+gtype+"'" alt='"'" width='"206'" height='"35'"></td>");
document.write('<div id="fadeshow1" style="margin-top:5px; margin-bottom:5px;"></div>')
writeButton("","/page5.html","p_ClipFrame",206,20,"Clip Frames","",0);

我做了一个例子,在页面上向div添加了一个图像。一个使用jQuery,另一个仅使用纯JavaScript。你可以在这里看到它的作用:http://jsfiddle.net/j6dZf/

// example 1: using normal javascript
// create a variable with the image url (not required)
var src = "http://upload.wikimedia.org/wikipedia/commons/thumb/a/af/Golden_retriever_eating_pigs_foot.jpg/170px-Golden_retriever_eating_pigs_foot.jpg";
// remember id's must be unique per page
// here i'm taking the container div and saving it
var container = document.getElementById("container");
// here i create a new image, set the src attribute and append to container
var img = new Image();
img.src = src;
container.appendChild(img);

这是jQuery版本

// example 2: using jquery
$(function() { // usually you wrap jQuery in this sort of thing
    var $container = $("#container") // grab container using jQuery
    var $img = $("<img>", {src: src}); // create an image tag with src set
    $container.append($img); // add the image you create, could just add text
})

不要使用document.write,而是使用document.createElement,然后用appendChild将生成的结构附加到文档中。你会有更好的结果。

您还应该使用CSS控制项目在页面上的显示位置。您可以通过JavaScript以编程方式分配这些,也可以提供类和id并将它们链接到预定义的CSS样式表。

好的,让我们看看这里。这里有几个建议/问题。希望其中一两个能有所帮助。

  1. 为什么要使用document.write()
  2. 为什么你有内联CSS?你能把它分开吗
  3. writeButton()函数的作用是什么
  4. 您是否使用了类似jQuery的东西,这可能会使您的DOM工作更轻松
  5. 您在同一页面上只能有一个ID!看起来您添加了两次
  6. 你说的"下一页"是什么意思
  7. 你有没有想过使用position: absolute,它会给你更多的权力在页面中移动<div>
  8. 您可以使用element.appendChild而不是document.write<div>放在DOM中的另一个位置。(请参见:https://developer.mozilla.org/en/DOM/element.appendChild)