如何用jQuery在p标签内随机位置插入随机长度涂黑span
实现文本随机位置的涂黑遮挡效果
你的代码目前只是把固定长度的涂黑块追加到段落末尾,没实现「随机位置+随机长度」的遮挡效果。下面是改进后的实现:
核心思路
- 对每个段落单独处理,避免所有段落效果一致
- 在段落文本的随机字符位置开始,生成随机长度的涂黑块
- 把段落内容拆分为「未遮挡部分」+「涂黑span」+「剩余未遮挡部分」,重新组合
完整代码
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <div class="ins"> <p>To forgive is to set a prisoner free and discover that the prisoner was you. You gain strength, courage and confidence by every experience in which you really stop to look fear in the face. You must do the thing which you think you cannot do.</p> <p>The unexamined life is not worth living. You gain strength, courage and confidence by every experience in which you really stop to look fear in the face. You must do the thing which you think you cannot do.</p> <p>Nothing is a waste of time if you use the experience wisely. A man who won't die for something is not fit to live.</p> </div>
CSS
body { font: normal normal 400 14pt/1.15em 'Courier New', monospace; } .blackout { color: #000; background-color: #000; /* 确保和文本高度对齐 */ display: inline-block; line-height: 1; } .ins { width: 100%; max-width: 1400px; margin: 0 auto; }
JavaScript
$(document).ready(function() { // 遍历每个p标签 $("p").each(function() { const $p = $(this); const text = $p.text(); // 文本太短就不处理 if (text.length < 10) return; // 生成随机起始位置(避免太靠近开头或结尾) const startPos = Math.floor(Math.random() * (text.length - 10)) + 2; // 生成随机遮挡长度:3-10个字符 const blockLength = Math.floor(Math.random() * 8) + 3; // 确保遮挡不会超出文本范围 const endPos = Math.min(startPos + blockLength, text.length); // 拆分文本并插入涂黑span const firstPart = text.slice(0, startPos); const blockedPart = `<span class="blackout">${text.slice(startPos, endPos)}</span>`; const lastPart = text.slice(endPos); // 替换原段落内容 $p.html(firstPart + blockedPart + lastPart); }); });
关键细节说明
- 给
.blackout加了display: inline-block和line-height: 1,确保涂黑块和文本高度完全对齐 - 限制了起始位置和遮挡长度的范围,避免遮挡出现在文本边缘或超出文本长度
- 每个段落独立生成随机参数,保证每个段落的遮挡效果都不一样
内容的提问来源于stack exchange,提问作者Womp
相关产品推荐
相关产品推荐

