jQuery如何移除p标签且不丢失超链接同时保证read more与文本相邻
长文本截断展开功能实现方案
一、核心优化点
- 移除p标签依赖:直接读取
.myClass容器的完整内容,新增安全截断逻辑避免切割HTML标签,保证原有超链接功能完全正常 - 按钮不换行错位:给「Read more」按钮添加行内显示样式,强制和前面的文本在同一行展示,不会出现错位
二、修正后完整代码
JS代码
var show_char = 280; var ellipses = "... "; var content = $(".myClass").html().trim(); // 安全截断HTML辅助函数,避免切断标签导致超链接失效 function safeTruncateHtml(html, maxLength) { let tempDiv = document.createElement('div'); tempDiv.innerHTML = html; let textCount = 0; let firstPart = ''; let isOverflow = false; // 递归遍历节点处理 function traverseNode(node) { if (isOverflow) return; // 文本节点直接计算长度截取 if (node.nodeType === Node.TEXT_NODE) { const text = node.textContent; if (textCount + text.length <= maxLength) { firstPart += text; textCount += text.length; } else { firstPart += text.substr(0, maxLength - textCount); textCount = maxLength; isOverflow = true; } return; } // 元素节点保留完整标签 const tagStart = node.outerHTML.match(/^<[^>]+>/)[0]; firstPart += tagStart; // 遍历子节点 for (let i = 0; i < node.childNodes.length; i++) { traverseNode(node.childNodes[i]); if (isOverflow) break; } // 未超出长度时闭合标签 if (!isOverflow) { const tagEnd = node.outerHTML.match(/<\/[^>]+>$/)[0]; firstPart += tagEnd; } } for (let i = 0; i < tempDiv.childNodes.length; i++) { traverseNode(tempDiv.childNodes[i]); if (isOverflow) break; } // 截取后半段内容 const fullText = tempDiv.textContent; const lastPart = html.substr(fullText.substr(0, textCount).length); return { firstPart, lastPart }; } if (content.length > show_char) { const truncateRes = safeTruncateHtml(content, show_char); const renderHtml = `${truncateRes.firstPart}<span class="ellipsis">${ellipses}</span><span class="hidden-content" style="display:none">${truncateRes.lastPart}</span><a class="read-more" href="#" style="display:inline-block;margin-left:4px;">Read more</a>`; $(".myClass").html(renderHtml); } $(".read-more").click(function(e) { e.preventDefault(); $(this).text() === "Read more" ? $(this).text(" Read less") : $(this).text("Read more"); $(".myClass .ellipsis, .myClass .hidden-content").toggle(); });
HTML代码
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="myClass"> <p><a href="#">演示链接</a> is a question and answer site for professional and enthusiast programmers. It features questions and answers on a wide range of topics in computer programming. It was created to be a more open alternative to earlier question and answer sites such as Experts-Exchange.</p> </div>
三、优化说明
- 完全不依赖p标签,
.myClass容器下不管是p、div还是其他嵌套标签都可以正常适配 - 安全截断逻辑不会切割
<a>等HTML标签,原有超链接的跳转、样式都完全保留 - 按钮添加了
display:inline-block样式,永远和前面的文本相邻,不会出现换行错位 - 修复了原有代码截断后半段内容的逻辑错误,截断位置更准确,不会出现内容丢失、重复的问题
内容的提问来源于stack exchange,提问作者user16121692
相关产品推荐
相关产品推荐

