在本文中,我们将学习如何使用 CSS 和 JavaScript 实现一个简单的文字溢出隐藏效果,当鼠标悬停在文本上时显示完整内容。
创建 HTML 页面结构
首先,我们需要创建一个包含文本内容的 HTML 页面。
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Text Overflow Hover Effect</title><link rel="stylesheet" href="styles.css">
</head>
<body><h1 class="text-overflow">This is a long text that will overflow and hide when it exceeds the container width.</h1><script src="scripts.js"></script>
</body>
</html>
添加 CSS 样式
接下来,我们为页面添加一些基本的样式以及实现文字溢出隐藏的效果。创建一个名为 styles.css
的文件,并添加以下内容:
body {font-family: Arial, sans-serif;text-align: center;
}.text-overflow {width: 300px;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;
}
在这里,我们设置了一个固定宽度的容器(width: 300px
),并使用 white-space: nowrap
、overflow: hidden
和 text-overflow: ellipsis
实现文字溢出隐藏效果。
编写 JavaScript 代码
现在我们已经准备好编写 JavaScript 代码来实现鼠标悬停时显示完整文本的效果。首先创建一个名为 scripts.js
的文件,然后添加以下代码:
document.querySelector('.text-overflow').addEventListener('mouseover', function () {this.style.whiteSpace = 'normal';
});document.querySelector('.text-overflow').addEventListener('mouseout', function () {this.style.whiteSpace = 'nowrap';
});
在这里,我们为 .text-overflow
元素添加了两个事件监听器:当鼠标悬停在文本上时,设置 white-space
为 normal
以显示完整内容;当鼠标离开时,设置 white-space
为 nowrap
以恢复溢出隐藏效果。