如何用jquery将相对定位的元素居中?
我正在尝试创建一个函数,它返回“左值应该是什么以使当前元素居中”。这允许我将动画设置到中心(和返回)或简单地将项目居中。
不过,我在相对定位部分遇到了麻烦。我错过了什么?
谢谢!
jQuery.fn.centerHorizontalOffset = function () {
var position = $(this).css("position");
if (position == "relative"){
return (($(window).width() - $(this).width()) / 2) - $(this).parent().offset().left;
} else if (position == "absolute"){
return ($(window).width() - $(this).width()) / 2;
}
return ($(window).width() - $(this).width()) / 2;
}
jQuery.fn.centerHorizontalDistance = function () {
return $(this).centerHorizontalOffset()-$(this).position().left;
}
$('#myDiv').css('left', $('#myDiv').centerHorizontalDistance());
I am trying to make a function which returns "what the left value should be to center the current element". This allows me to animate to the center (and back) or to simply center an item.
I am having trouble with the relative positioning part though. What did I miss?
Thanks!
jQuery.fn.centerHorizontalOffset = function () {
var position = $(this).css("position");
if (position == "relative"){
return (($(window).width() - $(this).width()) / 2) - $(this).parent().offset().left;
} else if (position == "absolute"){
return ($(window).width() - $(this).width()) / 2;
}
return ($(window).width() - $(this).width()) / 2;
}
jQuery.fn.centerHorizontalDistance = function () {
return $(this).centerHorizontalOffset()-$(this).position().left;
}
$('#myDiv').css('left', $('#myDiv').centerHorizontalDistance());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我会考虑使用 jQuery UI 的新“Position”插件: http://jqueryui.com/demos/position/< /a> - 它非常适合做你想做的事。
...我知道这不是对你的问题的直接回答,但这节省了我大量的时间,为什么要重新发明轮子呢? =)。祝你好运!
I would look into using jQuery UI's new "Position" plugin: http://jqueryui.com/demos/position/ - it's great at doing exactly what you're after.
...not a direct answer to your question I know, but this has saved me a ton of time, and why re-invent the wheel? =). Good luck!