jQuery关键词高亮是一种在前端网页中实现文本关键词高亮显示的技术。通过使用jQuery库,可以方便地操作DOM元素,从而实现对特定关键词的标记和高亮显示。
<span>
)包裹关键词,从而实现高亮。以下是一个简单的jQuery关键词高亮的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Keyword Highlighting</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<div id="content">
This is a sample text where we will highlight the keyword 'sample'.
</div>
<script>
$(document).ready(function() {
var keyword = 'sample';
var content = $('#content').text();
var highlightedContent = content.replace(new RegExp('(' + keyword + ')', 'gi'), '<span class="highlight">$1</span>');
$('#content').html(highlightedContent);
});
</script>
</body>
</html>
display: inline-block
等CSS属性来控制布局。通过以上方法,可以有效地实现和解决jQuery关键词高亮的相关问题。
领取专属 10元无门槛券
手把手带您无忧上云