Skip to content

Instantly share code, notes, and snippets.

@hjzheng
Created October 21, 2016 04:27
Show Gist options
  • Save hjzheng/2b7ae7ccd01ec025e429e9ffc9723d5e to your computer and use it in GitHub Desktop.
Save hjzheng/2b7ae7ccd01ec025e429e9ffc9723d5e to your computer and use it in GitHub Desktop.
判断内容是否溢出
const chopStyle2Num = style => Number(style.substr(0, style.length - 2));
const closestParent = (element, tagName) => {
let parentNode = element.parentNode;
while (parentNode.nodeName.toLowerCase() !== tagName) {
parentNode = parentNode.parentNode;
if (parentNode === document.body) {
parentNode = null;
break;
}
}
return parentNode;
};
const isContentOverflow = (element, content) => {
// 创建临时span
const span = document.createElement('span');
span.innerHTML = content;
span.style.opacity = 0;
document.body.appendChild(span);
const paddingSides = chopStyle2Num(window.getComputedStyle(element).getPropertyValue('padding-left')) + chopStyle2Num(window.getComputedStyle(element).getPropertyValue('padding-right'));
// 得到文本是否超出的flag
const isOverflow = span.offsetWidth > element.clientWidth - paddingSides;
// 移除临时元素
document.body.removeChild(span);
return isOverflow;
};
export {
chopStyle2Num,
closestParent,
isContentOverflow
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment