<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 200px;
height: 23px;
border: 1px solid #ccc;
white-space: nowrap;
overflow: hidden;
}
.text {
text-overflow: ellipsis;
}
</style>
</head>
<body>
<span>请输入:</span>
<input type="text" id="ipt" oninput="handleInput()">
<hr>
<div class="box">
<span id="text"></span>
</div>
</body>
<script>
let text = document.getElementById("text")
let inputDom = document.getElementById('ipt')
let parentDom = document.querySelector('.box')
// 判断某个盒子的文本是否超出父盒子
function onText(textDom) {
let parentWidth = textDom.parentNode.offsetWidth;
let contentWidth = textDom.offsetWidth;
if (contentWidth > parentWidth) { // 超出
parentDom.classList.add('text') // 添加文本省略号样式
} else { // 未超出
parentDom.classList.remove('text')
}
}
function handleInput() {
let value = inputDom.value
text.innerText = value
onText(text)
}
</script>
</html>
效果图: