<div class="single-line-container">
<div class="single-line-text">
我是一个名字很长很长很长很长的.pdf
</div>
<div class="extension">.pdf</div>
</div>
<div>
是否被截断:
<span class="single-line-text-result"></span>
</div>
body {
padding: 20px;
}
.single-line-container {
display: flex;
margin: 20px 0;
width: 200px;
resize: horizontal;
overflow: hidden;
border: 1px solid #000;
}
.single-line-text {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.extension {
display: none;
}
/**
* 单行
*/
const isTruncated = el => {
return el.scrollWidth > el.clientWidth;
};
const element = document.querySelector(".single-line-text");
const detect = () => {
const truncated = isTruncated(element);
document.querySelector(".extension").style.display = truncated
? "block"
: "none";
document.querySelector(".single-line-text-result").innerHTML = `${truncated}`;
};
detect();
const ro = new ResizeObserver(entries => {
detect();
});
ro.observe(document.querySelector(".single-line-text"));
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.