jQuery: adding element with dynamically calculated top property
In order to perform some animations I need to add a second image,开发者_Python百科 identical to the one I already have in my document, with the value of top
property equal to the height of the image.
Right now I do:
$("#blur").after("<img src='someimg.jpg' id='above' >");
var t = -($("#blur").height());
$("#above").animate({top: t}, 1);
But it's rather ugly - one can see the moment when new element is created and then moved to the right position.
Is there any way to place the second <IMG>
with automatically calculated top
walue?
My goal is to have two identical images stacked one over the another.
Sure, just set the 'top' CSS style property before adding the new image to the DOM:
var t = $('#blur').height();
$('<img src="someimg.jpg" id="above">')
.css('top', -t)
.insertAfter('#blur');
In practice though, it's better to set the position
attribute to absolute
, since otherwise that top
attribute will be relative to the element's default position, instead of relative to the origin of the first image.
var t = $('#blur').height();
$('<img src="someimg.jpg" id="above">')
.css({
position:'absolute',
top: 0, left: 0 // should be implicit anyway
})
.insertAfter('#blur');
p.s. use single quotes around your strings and HTML snippets, so that you can use the correct double-quote character for HTML attributes.
EDIT - for a more general solution (see http://jsfiddle.net/bE7TH/)
function overlay(selector, new_id) {
$(selector)
.clone()
.removeAttr('id')
.attr('id', new_id)
.css({
position: 'absolute', left: 0, top: 0
})
.insertAfter(selector);
}
I think the original element will have to have a position
property of fixed
or absolute
for this to work properly, and you may also need to account for any margin or padding too.
精彩评论