[英]How to display paragraphs and images from div in order?
I am building a small web-tool where editors can write content by using buttons to add paragraphs and images.我正在构建一个小型网络工具,编辑人员可以通过使用按钮添加段落和图像来编写内容。 I store the elements with an id ((number of element) starting at 0 and incremented for every new element) and load with a button in order to a div "preview" where the content is supposed to be displayed as in the web page later on.我存储带有 id 的元素((元素数量)从 0 开始并为每个新元素递增)并加载一个按钮以进行 div“预览”,内容应该在稍后显示在网页中在。
My issue is that, for a reason I don't understand, the image is always displayed below all the paragraphs instead of being in order.我的问题是,出于我不明白的原因,图像总是显示在所有段落下方,而不是按顺序显示。 Presumably there is an easy fix, but I am very new to HTML, CSS and JS and couldn't find the solution online.大概有一个简单的解决方法,但我对 HTML、CSS 和 JS 非常陌生,无法在线找到解决方案。 Sorry if this is a stupid mistake or the solution was already posted somewhere.抱歉,如果这是一个愚蠢的错误,或者解决方案已经发布在某处。
Javascript handling the preview rendering:处理预览渲染的 Javascript:
// Preview current document status
document.getElementById("previewButton").addEventListener("click", function() {
// Clear
document.getElementById("preview").innerHTML = "";
// Add all elements properly
var section = document.getElementById("preview");
var id = "preview";
for (var counter = 0; counter < element_counter; counter++) {
var type = document.getElementById(counter).nodeName;
// If text element
if (type === "TEXTAREA") {
var paragraph = document.createElement("p");
var text = document.getElementById(counter).value;
paragraph.setAttribute("id", id + counter);
paragraph.setAttribute("class", "flow-text");
paragraph.append(text);
section.appendChild(paragraph);
}
// If image element
if (type === "INPUT") {
var file = document.getElementById(counter).files[0];
var reader = new FileReader();
reader.onload = function(e) {
var image = document.createElement("img");
image.setAttribute("id", id + counter);
image.setAttribute("src", e.target.result);
image.setAttribute("class", "materialboxed responsive-img");
section.appendChild(image);
}
reader.readAsDataURL(file);
}
}
});
This might work.这可能会奏效。 I can't test though without your code.没有你的代码我无法测试。 However basically the principle at work is to isolate some of the vars so they represent distinct instantiations.然而,工作的基本原则是隔离一些变量,以便它们代表不同的实例。 And then immediately add the image element to the DOM.然后立即将图像元素添加到 DOM。 The reader.onload
is expected to run asynchronously still. reader.onload
预计仍会异步运行。
enter code here if (type === "INPUT") {
(function() {
var file = document.getElementById(counter).files[0];
var reader = new FileReader();
var image = document.createElement("img");
image.setAttribute("id", id + counter);
image.setAttribute("class", "materialboxed responsive-img");
section.appendChild(image);
reader.onload = function(e) {
image.setAttribute("src", e.target.result);
}
reader.readAsDataURL(file);
}());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.