admin管理员组文章数量:1336357
I have a div tag with id container. How can I find its center using either jquery or javascript?
<div id="container"></div>
here is css
#container {
width: 300px;
height: 300px;
border: 1px solid red;
}
I have a div tag with id container. How can I find its center using either jquery or javascript?
<div id="container"></div>
here is css
#container {
width: 300px;
height: 300px;
border: 1px solid red;
}
Share
Improve this question
asked Sep 11, 2012 at 14:08
Om3gaOm3ga
33k45 gold badges149 silver badges230 bronze badges
5
- 1 Find the centre relative to what? The element's top-left corner, the top-left corner of the page..? – David Thomas Commented Sep 11, 2012 at 14:09
- the element's top left corner. – Om3ga Commented Sep 11, 2012 at 14:10
-
2
something like:
div = $('#container'); var center = new Array( div.width() / 2 , div.height() / 2 );
:) – alexbusu Commented Sep 11, 2012 at 14:10 -
2
@AlexanderV.B. I remend
width * 0.5
instead ofwidth / 2
because it is faster ;) – Ron van der Heijden Commented Sep 11, 2012 at 14:11 -
Note that
position()
is relative to the element's offset parent and thatoffset()
is relative to the document. If you want to know where the center of a div is on the screen, useoffset()
. – Shmiddty Commented Sep 11, 2012 at 14:21
4 Answers
Reset to default 6Is it this?
var cX = $('#container').offset().left + $('#container').width()/2;
var cY = $('#container').offset().top + $('#container').height()/2;
$(function(){
var $this = $("#container");
var offset = $this.offset();
var width = $this.width();
var height = $this.height();
var centerX = offset.left + width / 2;
var centerY = offset.top + height / 2;
console.log(centerX ,centerY)
})
You should check:
- width / outerWidth
- height / outerHeight
jQuery way:
var div = $('#container');
var divCoords = {
x : div.width() * 0.5 ,
y : div.height() * 0.5
};
本文标签: javascriptHow to find the center of the div using jqueryStack Overflow
版权声明:本文标题:javascript - How to find the center of the div using jquery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742355341a2459294.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论