jQueryでHTML要素の中央位置(座標)を取得します。
var left = $(element).offset().left;
var top = $(element).offset().top;
var width = $(element).width();
var height = $(element).height();
offsetCenterLeft = left+(width/2);
offsetCenterTop = top+(height/2);
jQuery 拡張版
jQuery.prototype.offsetCenter=function(){
var left = this.offset().left;
var top = this.offset().top;
var width = this.width();
var height = this.height();
left = left+(width/2);
top = top+(height/2);
return { top , left }
}
$(element).offsetCenter(); // {top:0, left:0}
DEMO
demo HTML CSS JS
<div id="get-offsetCenter_demo_offset"> </div>
<div id="get-offsetCenter_demo" style="display: inline-block; width: 100px; height: 100px; border: 1px solid; position: relative;"><em style="position: absolute; top: 50%; left: 50%; bottom: 50%; right: 50%; border: 1px solid;"> </em></div>
<div id="get-offsetCenter_demo_display"> </div>
window.addEventListener("load",function(){
jQuery.prototype.offsetCenter=function(){
var left = this.offset().left;
var top = this.offset().top;
var width = this.width();
var height = this.height();
left = left+(width/2);
top = top+(height/2);
return { top , left }
}
$("#get-offsetCenter_demo").on("mousemove",(e)=>{
$("#get-offsetCenter_demo_display").text(
JSON.stringify($("#get-offsetCenter_demo").offsetCenter())
);
})
})
$(document).on("mousemove",function(event){
$("#get-offsetCenter_demo_offset").text("y:"+event.pageY+",x:"+event.pageX);
});
補足
要素の横幅、縦幅の取得に.width(),.height()を使用していますが、paddingまたはmarginを設定している場合は.outerWidth(),.outerHeight()(.outerWidth(true),.outerHeight(true))を使用してください。