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);
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 come 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});
-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 coming 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;
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.