什么'这是在HTML中多次重复同一图像的最佳方式

What's the best way to repeat the same image multiple times in HTML?

本文关键字:图像 方式 最佳 HTML 什么      更新时间:2023-09-26

所以我的文档结构如下:

<p>Repeat image 5 times after this paragraph </p>
<p>Repeat the same image 25 times after this paragraph </p>
<p>Repeat the image again 100 times after this paragraph </p>

我现在添加图像的方法是在每个p元素后面使用script标记,并在该脚本的for循环中使用document.write。

我想将所有的JavaScript和jQuery与HTML分开。最好的方法是什么?

如果您想将JavaScript排除在HTML文件之外,我建议您使用JavaScript(.js文件)代码创建一个单独的文件,然后从您想要使用该JavaScript的.HTML文件中引用它,如下所示:

<script src="location_of_your_javascript_file/file_name.js"></script>

然后在.html文件中,为每个段落标记添加一个ID属性,该属性对于每个parahraph标记都是唯一的,如下所示:

<p id='unique_id'>....</p>
<p id='unique_id2'>....</p>

然后你可以在.js文件中写这样的东西:

function appendPhotosToParagraph(paragraph_id, how_many_times):
    var paragraph = document.getElementById(paragraph_id);
    for (var i = 0; i < how_many_times; i++) {
        paragraph.innerHTML += "<img src='location_of_your_photo_file/file_name.jpg'";
    }
appendPhotosToParagraph('unique_id', 5);
appendPhotosToParagraph('unique_id2', 25);

你基本上创建了一个函数,你将在每一段中调用它。函数通过唯一id查找段落元素,并将其分配给paragraph变量。然后,每次将<img>标记附加到段落的现有内容时,它都使用for循环来循环how_many_times

根据我所知,没有办法做这样的事情。您可以尝试使用Angular.JS,它在HTML中提供了一些基于Javascript数组的"循环特性"。例如:

angular.module('testing',[])
.controller('TestCtrl', function($scope) {
  $scope.paragraphs = ["p1","p2","p3"];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="testing">
  <div ng-controller="TestCtrl">
    <p ng-repeat="p in paragraphs">
      {{ p }}
    </p>
  </div>
</body>

替换图像的段落。

Css?如果图像大小为100*100px

  1. 添加div
  2. 为其设置背景(图像)
  3. 设置宽度=100px
  4. 设置高度500px(需要重复100*次)

    p.repeat25+div.image{宽度:100px;高度:2500px;背景:url(image.png);}