在HTML中自定义单词标记可以通过多种方式实现,主要依赖于CSS和HTML的组合使用。以下是几种常见的方法:
<span>
元素<span>
元素是一个内联元素,可以用来包裹文本,并通过CSS来应用样式。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Word Marking</title>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
</head>
<body>
<p>This is a <span class="highlight">sample</span> text with some words highlighted.</p>
</body>
</html>
<mark>
元素HTML5 提供了 <mark>
元素,专门用于标记文本中的某些部分,使其更加显眼。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Word Marking</title>
</head>
<body>
<p>This is a <mark>sample</mark> text with some words marked.</p>
</body>
</html>
通过JavaScript可以动态地选择文本并应用自定义样式。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Word Marking</title>
<style>
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
</head>
<body>
<p id="text">This is a sample text with some words to be highlighted.</p>
<script>
document.addEventListener("DOMContentLoaded", function() {
const textElement = document.getElementById('text');
const text = textElement.innerHTML;
const highlightedText = text.replace(/sample/g, '<span class="highlight">sample</span>');
textElement.innerHTML = highlightedText;
});
</script>
</body>
</html>
!important
声明。<mark>
元素或特定CSS属性。通过以上方法,你可以灵活地在HTML中实现自定义单词标记,并根据具体需求选择最适合的方案。
领取专属 10元无门槛券
手把手带您无忧上云