[英]Place image on top of keywords
Let's say I have a div: 假设我有一个div:
<div id="mainContent">some random text. bla bla bla.</div>
let's say that the keword in this example is the word random
. 假设本例中的词是
random
。 how could I place an image on top of that word? 我如何在该单词的顶部放置图片?
In other words I will have to find that div with JavaScript then use a regular expression to find the keyword and then maybe wrap that keyword inside a span placing an img tag inside with it's position set to absolute. 换句话说,我将不得不使用JavaScript查找div,然后使用正则表达式来找到关键字,然后将其包装在将img标记设置为绝对值的范围内。
I guess the hardest part in this is warping the keyword with a span? 我猜最难的部分是使关键字具有跨度吗?
moreover how could I place the image on the center of the word? 此外,我如何将图像放在单词的中心? do I have to wrap it on a table instead?
我必须将其包装在桌子上吗?
First, store the contents of the div with: 首先,使用以下命令存储div的内容:
var x = document.getElementById('abc').innerHTML;
Then, use regex to replace the keyword with span wrapped version. 然后,使用regex将关键字替换为span wrapd version。
var keyword = "test";
x.replace(keyword, "<span>"+keyword+"</span>");
Then swap it back in; 然后换回去;
document.getElementById('abc').innerHTML = x;
I think using this would be better: 我认为使用它会更好:
x.replace('\b'+ keyword +'\b', "<span>"+keyword+"</span>");
\\b match a word boundary. \\ b匹配单词边界。
For the answer you accepted, you have to know the id of the div that has the keyword. 对于您接受的答案,您必须知道具有关键字的div的ID。 This solution is a bit more dynamic and uses jquery to find all divs with your keyword so you could place images on all of them.
该解决方案更具动态性,并使用jquery查找带有关键字的所有div,因此您可以在所有图像上放置图像。
var keyword = "random";
var found = $('div:contains("' + keyword +'")');
$.each(found, function(){
var wrapper = '<span class="whatever">' + keyword + '</span>';
var oldHtml = $(this).html();
$(this).html(oldHtml.replace(keyword, wrapper));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.