英文 | https://www.geeksforgeeks.org/how-to-dynamically-get-the-content-width-of-a-div-using-angularjs/?ref=rp
div的内容寬度可以根據使用者要求使用clientWidth和scrollWidth屬性動态擷取。如果使用者想知道實際顯示内容所需的空間(包括填充所占用的空間,但不包括滾動條,邊距或邊框),則使用者可以使用以下任何過程将傳回内容的整個内容的寬度。元件。
- 使用Element.ClientWidth屬性
- 使用Element.scrollWidth屬性
示例1:使用ClientWidth屬性的div的Content Width将傳回元素整個内容的寬度。
<!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>Geeting 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:使用scrollWidth屬性的div的Content Width将傳回元素的整個内容的寬度。
<!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>
最終效果截圖如下: