美文网首页
js实现文字展开和收起效果

js实现文字展开和收起效果

作者: 用技术改变世界 | 来源:发表于2023-03-23 09:20 被阅读0次

原文连接:https://zhuanlan.zhihu.com/p/445355066

二、js实现不足n行时,不展示省略号和展开,否则展示,满足兼容性

我们实现的思路就是在body插入一个dom,将文案循环加入,查看dom的高度,是否超过了lineHeight*n的高度,实现方案如下util.js

/** * * @param {原始element元素} originEle * @param {展示几行展示不开,折叠} rows * @param {文案} content * @param {展开的文案,默认 展开} fixedContent * @param {省略号文案,默认 ...} ellipsisStr */ window.measure = ( originEle, rows, content, fixedContent, ellipsisStr ) => { // 用来计算所占高度的dom元素 let ellipsisContainer = document.createElement('div'); ellipsisContainer.setAttribute('aria-hidden', 'true'); document.body.appendChild(ellipsisContainer); // 获取原始style const originStyle = window.getComputedStyle(originEle); const originCSS = styleToString(originStyle); const lineHeight = pxToNumber(originStyle.lineHeight); const maxHeight = lineHeight * (rows + 1) + pxToNumber(originStyle.paddingTop) + pxToNumber(originStyle.paddingBottom); // 设置样式,确保不会影响高度宽度的计算 { ellipsisContainer.setAttribute('style', originCSS); ellipsisContainer.style.position = 'fixed'; ellipsisContainer.style.left = '0'; ellipsisContainer.style.height = 'auto'; ellipsisContainer.style.minHeight = 'auto'; ellipsisContainer.style.maxHeight = 'auto'; ellipsisContainer.style.top = '-999999px'; ellipsisContainer.style.zIndex = '-1000'; ellipsisContainer.style.textOverflow = 'clip'; ellipsisContainer.style.whiteSpace = 'normal'; ellipsisContainer.style.webkitLineClamp = 'none'; } // 插入所有文案,去掉所有样式影响,看下是否可以装下所有内容 const wrapperStyle = `padding: 0;margin: 0;display: 'inline'; lineHeight: 'inherit';`; ellipsisContainer.innerHTML = `<div style=${wrapperStyle}><span style=${wrapperStyle}>${content}</span></div>`; // 如果可以装下所有内容,则跳过省略号计算 if (inRange()) { document.body.removeChild(ellipsisContainer); return { content, text: ellipsisContainer.innerHTML, ellipsis: false }; } // ========================= 查找匹配省略号内容 ========================= ellipsisContainer.innerHTML = ``; // 插入 省略号 const ellipsisTextNode = document.createTextNode(ellipsisStr); ellipsisContainer.appendChild(ellipsisTextNode); // 插入 展开 按钮 const fixedContentNode = document.createTextNode(fixedContent); ellipsisContainer.appendChild(fixedContentNode); // 插入 文案 const textNode = document.createTextNode(content); ellipsisContainer.appendChild(textNode); // 计算应该展示的文案 const result = measureText(textNode, content); document.body.removeChild(ellipsisContainer); return { content: ( result && result.reactNode ) || content, ellipsis: true, }; // 检查div的高度是否足以容纳内容 function inRange() { return ellipsisContainer.offsetHeight < maxHeight; } // 获得最大文本数 function measureText( textNode, fullText, startLoc = 0, endLoc = fullText.length, lastSuccessLoc = 0 ) { const midLoc = Math.floor((startLoc + endLoc) / 2); const currentText = fullText.slice(0, midLoc); textNode.textContent = currentText; if (startLoc >= endLoc - 1) { // 循环找出最小的step for (let step = endLoc; step >= startLoc; step -= 1) { const currentStepText = fullText.slice(0, step); textNode.textContent = currentStepText; if (inRange()) { return step === fullText.length ? { finished: false, reactNode: fullText, } : { finished: true, reactNode: currentStepText, }; } } } if (inRange()) { return measureText(textNode, fullText, midLoc, endLoc, midLoc); } return measureText(textNode, fullText, startLoc, midLoc, lastSuccessLoc); } // style转换成string function styleToString(style) { const styleNames = Array.prototype.slice.apply(style); return styleNames.map(name => `${name}: ${style.getPropertyValue(name)};`).join(''); } // px转换成数字 function pxToNumbe

r(value) { if (!value) return 0; const match = value.match(/^\d*(\.\d*)?/); return match ? Number(match[0]) : 0; } }

使用此方法如下<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src='./util.js' ></script> </head> <body> <div class="wrapper"> <div id='root' style='line-height: 14px;font-size: 12px;'></div> </div> <script> var fold = true; var unfoldText = '展开'; var foldText = '收起'; var ellipsisStr = '...'; var root = document.getElementById('root'); var text = 'css实现最多展示三行,展示不开用省略号表示,省略号和展开按钮有渐变背景色盖住底下文案。css实现最多展示三行,展示不开用省略号表示,省略号和展开按钮有渐变背景色盖住底下文案。css实现最多展示三行,展示不开用省略号表示,省略号和展开按钮有渐变背景色盖住底下文案。'; var result = window.measure(root, 3, text, unfoldText, ellipsisStr); renderRealContext(result); function renderRealContext (result) { const { content, ellipsis } = result; if(ellipsis){ if(fold){ root.innerHTML = `${content}${ellipsisStr}<span id='fold' style="color: #3498f7;">${unfoldText}</span>`; } else { root.innerHTML = `${text}<span id='fold' style="color: #3498f7;">${foldText}</span>`; } document.getElementById('fold').addEventListener('click', ()=>{ window.fold = !window.fold; renderRealContext(result); }) }else{ root.innerHTML = text; } } </script> </body> </html>效果如下展开的效果如下当不足3行时,效果如下

相关文章

网友评论

      本文标题:js实现文字展开和收起效果

      本文链接:https://www.haomeiwen.com/subject/dzcirdtx.html