我有一个不寻常的任务,我必须从 anchor 获取 px(x,y) 中的文本位置,但我不知道如何做到这一点:
这是 anchor 的图像:
这里是代码:
<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 中有什么方法可以做到这一点吗?我正在考虑将 span 包裹在文本周围,并使用 js 获取 offsetWidth/offsetHeight,但这只会得到我的大小,而不是 anchor 中文本的位置。
更新:狂野结果
我稍微改变了代码:
<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(不能是 anchor 大小的 5 倍)
如果我在js中使用它:
var TextTop = document.getElementById('<%= anchorText.ClientID %>').offsetTop;
var TextLeft = document.getElementById('<%= anchorText.ClientID %>').offsetLeft;
我得到:
anchor 文本顶部 = 100 anchor 文本左 = 201
这可能是因为控件被标记为 runat="server"吗?
最佳答案
您无法获取元素内文本的位置。您需要将文本包装在 <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;
输出:
关于c# - ASP.NET 从 anchor 获取以 px 为单位的文本位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9032933/