1

HTMLボタンのテキストの位置について質問があります。ご覧のとおり、左上隅の要素の位置を取得する方法はありますが、右上隅はどうでしょうか。例えば

私は次のようなボタンを持っています:

<button style="text-align: left">Hello World</button>

... OK次に、内側のテキスト「HelloWorld」がどの座標で終了するのか知りたいです。それで、jsでそれを取得することは可能ですか、それとも最も最適な方法は何ですか?

ありがとう

4

2 に答える 2

2

これを試して:

純粋な JavaScript

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);

jQueryで

強くお勧めします。
http://jsfiddle.net/DerekL/AYAPY/


ここに画像の説明を入力

|返された座標が正しいことを示すために、ポイントに少し「 」を付けました。

于 2012-05-28T01:32:42.800 に答える
2

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);
于 2012-05-28T01:33:05.117 に答える