在 HTML 中插入图片内联文本

Insert image inline text in HTML

请原谅我在这方面的无知。我怎样才能将图像插入预格式化的 text/string in HTML/CSS/JAVASCRIPT,给出如下所示的字符串,其中字符串中的键表示图像位置?

Please insert into me <here> and <here>.
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
  <style>
    img {
        display: inline-block;
    }
</style>
</head>
<body>
  <p>Please insert into me <img src="your image source" alt="Your Image">  and <img src="your image source" alt="Your Other Image" >. </p>
</body>
</html>

我猜你必须用一个独特的词或短语来格式化文本,然后用图像代码替换这个词。

正如@Jaxo 所说。

Please insert into me [Img1] and [Img2].

然后用javascript把[Img1]和[Img2]替换成代码

一种干净的方法是创建您自己的 spritesheet,然后创建元素来保存您的图像。

编辑: 如果您还需要通过纯 js 动态进行替换,这里有一个简单的 JavaScript fiddle example.

我在这里也放了这个例子:我们定义唯一标签的样子(这是一个简单的标签),然后创建正则表达式来匹配它。使用 replace 方法,我们全局搜索并替换 /g 为我们想要的 html,并用替换结果更新我们的元素。

(function () {
  "use strict";
    
    function replaceTagWithImage() {
        var element = document.getElementById("my-paragraph"),
            icon = '<i class="icon-foo"></i>',
            iconTag = /\{image\}/g;
        element.innerHTML = element.innerHTML.replace(iconTag, icon);
    }
    
    replaceTagWithImage();
    
}());
.icon-foo {
  display: inline-block;
  width: 100px;
  height: 20px;   
  background-image: url("http://placehold.it/350x150");
  background-position: 0 0; 
}
<p id="my-paragraph">Please insert into me {image} and {image}.<p>

AngularJS 示例 - 两种方法 - 指令一种更可取。:

var myApp = angular.module("myApp", []);

myApp.controller("MainController", ["$scope", "$sce",
  function($scope, $sce) {
    $scope.myImage = $sce.trustAsHtml('<i class="icon-foo"></i>');
  }
]);

myApp.directive("myImg", function() {
  return {
    restrict: "E",
    replace: true,
    template: '<i class="icon-foo"></i>'
  };
});
.icon-foo {
  display: inline-block;
  width: 100px;
  height: 20px;
  background-image: url("http://placehold.it/350x150");
  background-position: 0 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<html ng-app="myApp">
<head>
  <title>Angular example</title>
</head>
<body>
  <div>
    <div ng-controller="MainController">
      <p>Please insert into me <my-img></my-img> and <my-img></my-img>.</p>
      <br />
      <p>Inserting html from controller: <span ng-bind-html="myImage"></span></p>
    </div>
  </div>
</body>
<html>

静态CSS/HTML示例:

.icon-foo {
  display: inline-block;
  width: 100px;
  height: 20px; 
  background-image: url("http://placehold.it/350x150");
  background-position: 0 0; 
}
Please insert into me <i class="icon-foo"></i> and <i class="icon-foo"></i>.