[英]Getting the width of a newly added element
我需要使用JavaScript或jQuery獲取新添加項的寬度。 我知道如果我需要將事件綁定到新添加的元素,我可以在jQuery中使用事件委托或.on()方法。 但在這種情況下,我沒有綁定一個事件,我只需要獲得該元素的寬度。 我怎樣才能做到這一點?
$('#box').width(); // won’t work
document.getElementById("box").width; // won't work either
你可以使用jQuery的.width()
方法:
$('#box').width() // Should give you the pixel width with no px/rem/%
// Or plain ol' Vanilla JS
document.getElementById('box').offsetWidth
// Or mix it up
$('#box')[0].offsetWidth
確保您的腳本位於頁面底部和/或您正在使用jQuery的.ready()
方法:
$(document).ready(function(){
$('#box').width();
});
// Shorthand for the above
$(function(){
$('#box').width();
});
如果有人能想到其他問題或解決方案,請為答案做出貢獻。
嘗試這個:
var box = document.getElementById('box');
alert(window.getComputedStyle(box).width);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.