【问题标题】:Replace text with an image in javascript用javascript中的图像替换文本
【发布时间】:2019-10-15 02:28:43
【问题描述】:
我正在寻找一种在 javascript 中用图像替换文本的方法,但我做不到,
例如文字:
<div><p class="YellowTxt">MyYellowTxt</p></div>
<div><p class="BlueTxt">MyBlueTxt</p></div>
<div><p class="GreenTxt">MyGreenTxt</p></div>
要有一个黄色、蓝色和绿色的图像。
【问题讨论】:
标签:
javascript
image
text
replace
【解决方案1】:
使用innerHTML:
function replace() {
var el = document.getElementsByClassName('YellowTxt')[0]
el.innerHTML = '<img src="" alt="image"/>'
}
<div>
<p class="YellowTxt">MyYellowTxt</p>
</div>
<div>
<p class="BlueTxt">MyBlueTxt</p>
</div>
<div>
<p class="GreenTxt">MyGreenTxt</p>
</div>
<hr />
<button onclick="replace()">Replace</button>