简体   繁体   English

jQuery - 如果元素被隐藏,$(this).width() 不起作用!

[英]jQuery - $(this).width() doesn't work if the element is hidden!

How can I get the width (set in the css styles) of a element that is hidden?如何获取隐藏元素的宽度(以 css 样式设置)?

css: css:

a{
  position: absolute;
  width: 40px;
  height: 40px;
  background: pink;
}

js: js:

var nav = $('.nav');
nav.hide();

nav.hover(function(){
  nav.stop().animate({opacity: 1}, 300);
}, function(){
  nav.stop().animate({opacity: 0}, 500);
});

$('<a>', {
css: { left: 940 / 2 - ($(this).width() / 2), // <-- here it seems to be 0
click: function(){
    alert($(this).width()); // here it works
    return false;
  }
}).appendTo(nav);

This may be impossible, because $(this) refers to the window object in this case and not the <a> element.这可能是不可能的,因为在这种情况下$(this)指的是window object 而不是<a>元素。 The this reference will be properly bound to the newly created element only if called in the context of a function.只有在 function 的上下文中调用时, this引用才会正确绑定到新创建的元素。

There might be a way to inject the element into this using closures but I can't figure out how - interested to see whether somebody can come up with a solution.可能有一种方法可以使用闭包将元素注入this ,但我不知道如何 - 有兴趣看看是否有人能提出解决方案。

Until then, this alternative is less elegant, but will always work:在那之前,这个替代方案不太优雅,但总是有效:

mylink = $('<a>', {
    id: 'test',
   click: function(){
   alert($(this).width()); // here it works
   return false;
 }
}).appendTo($("body")).html("Test");;

mylink.css({ left: mylink.width() / 2});

JSFiddle JSFiddle

-Assuming that you want the width of the.nav element (the element that has been hidden). - 假设您想要.nav 元素(已隐藏的元素)的宽度。

since you are using $('<a>') you are actually creating an anchor tag and in that case $(this) will refer to the anchor element and not the.nav element and so its width is coming out to be 0.由于您使用的是$('<a>')您实际上是在创建一个锚标记,在这种情况下 $(this) 将引用锚元素而不是 .nav 元素,因此它的宽度为 0。

if you wish to get the width of the.nav element u can use如果你想获得 .nav 元素的宽度,你可以使用

$('.nav').width(); and this will get you the width of the matched elements.这将为您提供匹配元素的宽度。

Try this please:请试试这个:

$('a').click(function(){
    $(this).appendTo(nav);
    alert($(this).width());
    $(this).css('left', ($(this).width() / 2));
    return false;
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM