如何确定HTML元素的内容是否溢出
给定一个HTML元素,任务是使用JavaScript确定其内容是否溢出。
方法:
- 选择要检查溢出的元素。
- 检查其style.overflow属性,如果是“visible”,则元素是隐藏的。
- 同时,检查其clientWidth是否小于scrollWidth或clientHeight是否小于scrollHeight,如果是,则元素溢出。
示例1: 在这个示例中,检查段落(p
元素)的内容是否溢出。
<!DOCTYPE HTML>
<html>
<head>
<title>
How to determine the content of
HTML elements overflow or not
</title>
<style>
#GFG_UP {
font-size: 16px;
font-weight: bold;
border: 1px solid black;
height: 20px;
width: 200px;
margin: 0 auto;
}
</style>
</head>
<body style = "text-align:center;">
<h1 style = "color:green;" >
GeeksForGeeks
</h1>
<p id = "GFG_UP"></p>
<br><br>
<button onclick = "gfg_Run()">
Click here
</button>
<p id = "GFG_DOWN" style =
"color:green; font-size: 20px; font-weight: bold;">
</p>
<script>
var el_up = document.getElementById("GFG_UP");
var el_down = document.getElementById("GFG_DOWN");
var str = "Click on button to check OverFlow";
el_up.innerHTML = str;
function check(el) {
var curOverf = el.style.overflow;
if ( !curOverf || curOverf === "visible" )
el.style.overflow = "hidden";
var isOverflowing = el.clientWidth < el.scrollWidth
|| el.clientHeight < el.scrollHeight;
el.style.overflow = curOverf;
return isOverflowing;
}
function gfg_Run() {
ans = "No Overflow";
if (check(el_up)) {
ans = "Content Overflowed";
}
el_down.innerHTML = ans;
}
</script>
</body>
</html>
输出:
- 点击按钮之前:
- 点击按钮之后:
示例2: 这与前一个示例相同,但是这里段落的内容(
元素)没有溢出,因此示例检查并显示所需的输出 没有溢出 。
<!DOCTYPE HTML>
<html>
<head>
<title>
How to determine the content of
HTML elements overflow or not
</title>
<style>
#GFG_UP {
font-size: 16px;
font-weight: bold;
border: 1px solid black;
height: 20px;
width: 200px;
margin: 0 auto;
}
</style>
</head>
<body style = "text-align:center;">
<h1 style = "color:green;" >
GeeksForGeeks
</h1>
<p id = "GFG_UP"></p>
<br><br>
<button onclick = "gfg_Run()">
Click here
</button>
<p id = "GFG_DOWN" style =
"color:green; font-size: 20px; font-weight: bold;">
</p>
<script>
var el_up = document.getElementById("GFG_UP");
var el_down = document.getElementById("GFG_DOWN");
var str = "Click on button to check";
el_up.innerHTML = str;
function check(el) {
var curOverf = el.style.overflow;
if ( !curOverf || curOverf === "visible" )
el.style.overflow = "hidden";
var isOverflowing = el.clientWidth < el.scrollWidth
|| el.clientHeight < el.scrollHeight;
el.style.overflow = curOverf;
return isOverflowing;
}
function gfg_Run() {
ans = "No Overflow";
if (check(el_up)) {
ans = "Content Overflowed";
}
el_down.innerHTML = ans;
}
</script>
</body>
</html>
输出:
- 点击按钮之前:
- 点击按钮之后: