首页 > 解决方案 > 如何在html中多次重复相同的图像?

问题描述

我想在整个页面宽度上重复一个图像-“box1”。我尝试了以下方法,但它不起作用。

var count = $(window).width() / $("#box1").width();

for (var i = 1; i <= count; i++) {
  var paragraph = document.getElementById("top-section");
  paragraph.innerHTML += "<img src='images/box1.png' id='box1'html>";
}
#top-section {
  float: left;
}
<div id="top-section"></div>

标签: javascriptjqueryhtmlcss

解决方案


这个对我来说很好用。一探究竟...

只需克隆您需要的元素并将其附加到该部分中。

var count = $(window).width() / $(".box1").last().width();

for (var i = 1; i <= count; i++) {
  $("#top-section").append($(".box1").last().clone(true));
}
#top-section {
  float: left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="top-section">
  <img src="images/box1.png" class="box1">
</div>

推荐阅读