gpt4 book ai didi

javascript - 在 HTML 中插入图像内联文本

转载 作者:太空宇宙 更新时间:2023-11-03 21:32:22 24 4
gpt4 key购买 nike

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

Please insert into me <here> and <here>.

最佳答案

一种简洁的方法是创建您自己的 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>.

关于javascript - 在 HTML 中插入图像内联文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28614889/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com