HTMLボタンのテキストの位置について質問があります。ご覧のとおり、左上隅の要素の位置を取得する方法はありますが、右上隅はどうでしょうか。例えば
私は次のようなボタンを持っています:
<button style="text-align: left">Hello World</button>
... OK次に、内側のテキスト「HelloWorld」がどの座標で終了するのか知りたいです。それで、jsでそれを取得することは可能ですか、それとも最も最適な方法は何ですか?
ありがとう
HTMLボタンのテキストの位置について質問があります。ご覧のとおり、左上隅の要素の位置を取得する方法はありますが、右上隅はどうでしょうか。例えば
私は次のようなボタンを持っています:
<button style="text-align: left">Hello World</button>
... OK次に、内側のテキスト「HelloWorld」がどの座標で終了するのか知りたいです。それで、jsでそれを取得することは可能ですか、それとも最も最適な方法は何ですか?
ありがとう
これを試して:
http://jsfiddle.net/DerekL/AYAPY/3/
//1. wrap with content <span>
var txt=document.querySelector("button").innerHTML;
document.querySelector("button").innerHTML="";
document.querySelector("button").appendChild(document.createElement("span"));
document.querySelector("button span").innerHTML=txt;
//2. Get the <span>'s coordinate
var end_y=document.querySelector("button span").offsetTop;
var end_x=document.querySelector("button span").offsetLeft+document.querySelector("button span").offsetWidth;
//3. Done!
alert(end_x+", "+end_y);
強くお勧めします。
http://jsfiddle.net/DerekL/AYAPY/
|
返された座標が正しいことを示すために、ポイントに少し「 」を付けました。
getButtonCoords に要素を渡します。オブジェクトを返します( と呼びましょうcoords
)。coords.x
は x 座標、coords.y
は y 座標です。
/* from stackoverflow.com/questions/442404/dynamically-retrieve-html-element-x-y-position-with-javascript */
function getOffset( el ) {
var _x = 0;
var _y = 0;
while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
_x += el.offsetLeft - el.scrollLeft;
_y += el.offsetTop - el.scrollTop;
el = el.offsetParent;
}
return { top: _y, left: _x };
}
function getButtonCoords(button) {
/* wrap the text in a span element so we can get its coordinates */
button.innerHTML = "<span id='button-text-" + button.id + "'>" + button.innerHTML + "</span>";
/* get the span element */
var button_span = document.getElementById('button-text-' + button.id);
/* get the offset */
var offset = getOffset(button_span);
/* get the coordinates */
var coords = { x: offset.left + button_span.offsetWidth, y: offset.top };
/* return them */
return coords;
}
/* get the button and pass it to the coordinate function */
var coords = getButtonCoords(document.getElementById('button-id'));
/* show the results */
alert(coords.x + ", " + coords.y);