如何使用AngularJS动态地获得一个div的内容宽度
div的内容宽度可以根据用户需求使用clientWidth和scrollWidth属性动态获取。如果用户想知道实际显示的内容所需的空间,包括填充所占用的空间,但不包括滚动条、边距或边框,那么用户可以使用以下任何一个程序,它将返回一个元素的整个内容的宽度。
- 使用Element.ClientWidth属性
- 使用Element.scrollWidth属性
例子1: div的内容宽度使用ClientWidth属性将返回元素的整个内容的宽度。
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<style>
#div1 {
height: 100px;
width: 300px;
border: 2px solid black;
overflow: scroll;
}
h1 {
color: green;
}
</style>
</head>
<body>
<center>
<h1>GeeksforGeeks</h1>
<h3>Getting Content width</h3>
<div id="div1">
Calculate content width of a div on GeeksforGeek.
GeeksforGeeks is a computer science portal which
helps students to learn various programming language
and master data structures and algorithms. There are
various courses available to learn new skills.
</div>
<br>
<button onclick="contentwidth()">Content Width of Div</button>
<p id="p1"></p>
</center>
<script>
function contentwidth() {
var ans = "Content-width: "
+ angular.element(document.getElementById("div1").clientWidth)
+ "px<br>";
document.getElementById("p1").innerHTML = ans;
}
</script>
</body>
</html>
输出:
示例2: div的内容宽度使用scrollWidth属性将返回元素的整个内容的宽度。
<!DOCTYPE html>
<html>
<head>
<script src=
"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js">
</script>
<style>
#div1 {
height: 100px;
width: 300px;
border: 2px solid black;
overflow: scroll;
}
h1 {
color: green;
}
</style>
</head>
<body>
<center>
<h1>GeeksforGeeks</h1>
<h3>Getting Content width</h3>
<div id="div1">
Calculate content width of a div on GeeksforGeek.
GeeksforGeeks is a computer science portal which
helps students to learn various programming language
and master data structures and algorithms. There are
various courses available to learn new skills.
</div>
<br>
<button onclick="contentwidth()">Content Width of Div</button>
<p id="p1"></p>
</center>
<script>
function contentwidth() {
var ans = "Content-width: "
+ angular.element(document.getElementById("div1").scrollWidth)
+ "px<br>";
document.getElementById("p1").innerHTML = ans;
}
</script>
</body>
</html>
输出: