最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery - $(this).width() doesn't work if the element is hidden! - Stack Overflow

programmeradmin0浏览0评论

How can I get the width (set in the css styles) of a element that is hidden?

css:

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

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);

How can I get the width (set in the css styles) of a element that is hidden?

css:

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

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);
Share Improve this question edited May 2, 2011 at 10:09 Alexa asked May 2, 2011 at 9:39 AlexaAlexa 2251 gold badge3 silver badges7 bronze badges 2
  • Did you use visibility: hidden or display: none? – Joachim Sauer Commented May 2, 2011 at 9:41
  • I posted the code. It's not exactly like this, but its similar to what I have.. – Alexa Commented May 2, 2011 at 9:51
Add a ment  | 

3 Answers 3

Reset to default 3

This may be impossible, because $(this) refers to the window object in this case and not the <a> element. The this reference will be properly bound to the newly created element only if called in the context of a function.

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 e up with a solution.

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

-Assuming that you want the width of the .nav element (the element that has been hidden).

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 ing out to be 0.

if you wish to get the width of the .nav element u can use

$('.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;
})
发布评论

评论列表(0)

  1. 暂无评论