今天復習了一下關於getComputedStyle的用法,遇到了小小的挫折。報錯前的代碼:
<div class="box"> <div id="box1"> <input type="text"> <input type="text"> <input type="text"> </div> </div> <style> .box{ width: 300px; height: 200px; margin: 20px auto; border: 1px solid red; } #box1{ width: 100%; height: 100px; background:blue; margin: 5px auto; } </style> <script> window.onload=function(){ var box = document.getElementsByClassName('box'); alert(window.getComputedStyle(box,null).height) } </script>
當然,這只是隨便舉的例子,然而卻遇到了標題上面的報錯,糾結了一會后,終於解決了。原來是獲取dom元素時,應該通過標簽中的id屬性去獲取,這樣僅需要改為
var box = document.getElementById('box1')就OK啦,是不是很簡單。