ASP.NET Получить положение текста в пикселях из якоря - PullRequest
0 голосов
/ 27 января 2012

У меня необычное задание, мне нужно получить положение текста в px (x, y) из якоря, но я понятия не имею, как это сделать:

Вот изображение якоря:

enter image description here

Вот код:

<a id="anchor" href="#" runat="server" style="display: inline-block; border-color: #000000; text-decoration: none; border-style: solid; border-width: 1px; background-repeat:no-repeat; width:100px; height:50px;">Text</a>

Есть ли способ сделать это в ASP.NET или / и JavaScript?Я думал о том, чтобы обернуть область вокруг текста и получить offsetWidth / offsetHeight с помощью js, но это позволило бы получить только размер, а не положение текста в привязке.

ОБНОВЛЕНИЕ: Дикие результаты

Я немного изменил код:

    <div style="display:inline-block;">
                    <p class="category-label" align="center">Normal state preview</p>
                    <a id="anchor" href="#" runat="server" style="display: inline-block; border-color: #000000; text-decoration: none; border-style: solid; border-width: 1px; background-repeat:no-repeat; font-family:Arial; font-size:10px; color:#000000; width:100px; height:50px;">
                    <div runat="server" id="anchorText">Text</div></a>
                </div>

<input type="hidden" id="anchorTextTop" runat="server" />
<input type="hidden" id="anchorTextLeft" runat="server" />

Вот Js, которые я использую:

 function GetTextPosition() {

        var TextTop = document.getElementById('<%= anchorText.ClientID %>').offsetParent.offsetTop;
        var TextLeft = document.getElementById('<%= anchorText.ClientID %>').offsetParent.offsetLeft;

        document.getElementById('<%= anchorTextTop.ClientID %>').value = TextTop;
        document.getElementById('<%= anchorTextLeft.ClientID %>').value = TextLeft;
    }

значения, которые я получаю:

anchorTextTop = 78 (не может бытьэто всего несколько пикселей сверху) anchorextLeft = 541 (не может быть, это 5-кратный размер якоря)

, если я использую это в js:

var TextTop = document.getElementById('<%= anchorText.ClientID %>').offsetTop;
var TextLeft = document.getElementById('<%= anchorText.ClientID %>').offsetLeft;

Я получаю:

anchorTextTop = 100 anchorextLeft = 201

Может ли это быть потому, что элементы управления помечены runat = "server"?

Ответы [ 2 ]

2 голосов
/ 28 января 2012

Вы не можете получить положение текста внутри элемента.Вам нужно будет обернуть текст в <span> (или в строку <div>) и получить .offsetTop/.offsetLeft из <span>.Чтобы сместить относительно родителя, установите для родителя значение position: relative;.

Демо: http://jsfiddle.net/ThinkingStiff/wC4St/

HTML:

<div style="display:inline-block;">
    <p id="category-label" align="center">Normal state preview</p>
    <a id="anchor" href="#" runat="server" style="display: inline-block; border-color: #000000; text-decoration: none; border-style: solid; border-width: 1px; background-repeat:no-repeat; font-family:Arial; font-size:10px; color:#000000; width:100px; height:50px;">
    <span runat="server" id="anchorText">Text</span></a>
</div>

CSS:

#anchor {
    position: relative;   
    text-align: center; 
}

Скрипт:

document.getElementById( 'category-label' ).textContent = 
      'left: ' + document.getElementById( 'anchorText' ).offsetLeft 
    + ' top: ' + document.getElementById( 'anchorText' ).offsetTop;

Вывод:

enter image description here

1 голос
/ 27 января 2012

Вам придется сделать это с помощью скрипта на стороне клиента, потому что страница должна быть отображена браузером, прежде чем вы сможете работать с размерами макета.

способ вычисления позиции зависит от того, какую позицию вы хотите получитьбыть по отношению к.значения offsetTop и offsetHeight относятся к offsetParent элемента.

Если вы хотите, чтобы позиция элемента относилась к документу, вы можете пройти вверх по рекурсивным свойствам offsetParent до нулевого значения и увеличивать offsetTop.и свойства offsetLeft.

function getPosition()
{
    var element = document.getElementById("anchor");
    var position = {};
    position.top = element.offsetTop;
    position.left = element.offsetLeft;
    return position;
}
...