首页 > 解决方案 > 使用javascript将两个图像加载到html

问题描述

我想将两个图像加载到我的 HTML 页面并使用 Javascript 并排(水平)放置它们。但在第一步,就会发生混乱。

在这里,我有一个代码,结果如下:

在此处输入图像描述

我该如何解决?我的错在哪里?

Javascript:

var img = document.createElement("IMG");
  img.setAttribute("src", "1.jpg");
  img.setAttribute("width", "300");
  img.setAttribute("height", "300");
  img.setAttribute("alt", "The Pulpit Rock");
  document.body.appendChild(img);

  var img2 = document.createElement("IMG2");
  img2.setAttribute("src", "2.jpg");
  img2.setAttribute("width", "300");
  img2.setAttribute("height", "300");
  img2.setAttribute("alt", "The Pulpit Rock2");
  document.body.appendChild(img2);

HTML:

<div id="IMG">
<div id="IMG2">

<script src="Script.js"></script>
<link rel="stylesheet" type="text/css" href="Style.css">

CSS:

img {

   border: 1px solid #d6d6d6;
   padding: 6px;
   border-radius: 50%;
   box-shadow: 0 4px 8px 0 rgba(227, 228, 232), 0 6px 20px 0        rgba(227, 228, 232);  

}


img2 {

   border: 1px solid #d6d6d6;
   padding: 6px;
   border-radius: 50%;
   box-shadow: 0 4px 8px 0 rgba(227, 228, 232), 0 6px 20px 0        rgba(227, 228, 232);  

}

标签: javascripthtmlcss

解决方案


对于你的img2,你有var img2 = document.createElement("IMG2");,这将创建一个<img2>元素。这需要更改var img2 = document.createElement("IMG");为创建一个<img>元素。

这可以在下面看到:

var img = document.createElement("IMG");
img.setAttribute("src", "http://placehold.it/100");
img.setAttribute("width", "300");
img.setAttribute("height", "300");
img.setAttribute("alt", "The Pulpit Rock");
document.body.appendChild(img);

var img2 = document.createElement("IMG");
img2.setAttribute("src", "http://placehold.it/100");
img2.setAttribute("width", "300");
img2.setAttribute("height", "300");
img2.setAttribute("alt", "The Pulpit Rock2");
document.body.appendChild(img2);
img {
  border: 1px solid #d6d6d6;
  padding: 6px;
  border-radius: 50%;
  box-shadow: 0 4px 8px 0 rgba(227, 228, 232), 0 6px 20px 0 rgba(227, 228, 232);
}

img2 {
  border: 1px solid #d6d6d6;
  padding: 6px;
  border-radius: 50%;
  box-shadow: 0 4px 8px 0 rgba(227, 228, 232), 0 6px 20px 0 rgba(227, 228, 232);
}


推荐阅读