jQuery provides a way to get the position of an element:
var position = myElement.position();
However, this function is read only.
Is there 开发者_如何学编程a way to set the position of my element?
$("#element").offset({ top: XXX, left: YYY})
http://api.jquery.com/offset/
Yes, you would just add the appropriate css to the item:
// Example
myElement.css({ position: relative; top: -40, left: -40 });
To position you could use the CSS method:
$(element).css('left', '22px');
$(element).css({
left: '22px',
top: '10px'
});
This assumes you already have position:relative
or position:absolute
in your stylesheet. If not, you can add it as well just like you add left
or top
, right
or bottom
. Works with z-index
as well.
http://api.jquery.com/css/
$('selector').css({'position':'relative','top':'10px','left':'10px');
You can position only absolutely or relatively positioned elements by setting its top and left style properties. Use css
method and set the position
, top
and left
property of the element.
$("selector").css({
position: 'absolute',//Or relative
top: 100,
left: 100
});
If you're using jQuery UI in addition to jQuery, you can use the position
utility.
$(selector).position({
of: $(parent_selector), //position against
my: 'right', //element being positioned
at: 'center', //target element
...
});
The usual decision of this problem is to use .css()
method like:
$(".element").css({
position: absolute, //or relative
top: '50px',
left: '50px'
});
Functions like .position()
return object properties .top
and .left
, so you can also try the next:
$(".element").position().top = 50;
$(".element").position().top = 50;
I havn't tried the last way by my self, so I'm not sure if it works, but the first one exatly does.
No. JQuery cannot set the offset of an element. Instead, it can set the top and left properties of it. As well as it's position CSS property.
精彩评论