英文 | 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>
最终效果截图如下: