我有以下对象
<div class='app_advert'><a href="/apps">GET THE APPS</a></div>
我将其称为x
我试图自动定位在另一个元素(y
)之上,我想将对象的中间对齐,所以我的理论是这样的:
x_width = $(x).width();
y_width = $(y).width();
y_position = $(y).offset().left;
x_horizontal_position = y_position+(y_width/2)-(x_width/2)
我正在尝试使用以下方法获取x
的宽度:
jQuery(window).load(function(){
object_width = jQuery('.apps_advert').width();
console.log(object_width);
});
但它返回null
。
我还应用了以下 CSS,以防这可能会影响事情:
div.app_advert{
position: absolute;
display: none;
font-size: 17pt;
top: 0;
}
div.app_advert a{
color: white;
text-decoration: none;
}
最佳答案
你的类是app_advert
,但是你的jQuery代码试图找到apps_advert
(注意app
到apps的复数形式
)
所以尝试一下
object_width = jQuery('.app_advert').width();
关于javascript - width() 在 DOM 对象上返回 `null`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6411095/