使用 Internet Explorer 我想获得一个人点击文本的位置。 3 到 4 个字符的错误是可以的。 文本不可编辑,通常位于 span 元素中。
我知道我可以为 HTMLDocument 设置一个单击事件侦听器,但是我并不总是拥有 HTMLDocument 对象,因此可能会错过该事件。
我尝试获取 IHTMLSelectionObject,然后使用 IHTMLTxtRange 创建一个文本范围,但是当网页被简单地单击而不是至少选择 1 个字符时,IHTMLTxtRange 具有 HTMLBody 的父级,而不是被单击的元素的父级.
HTMLDocument.activeElement 也不可靠。 在我的测试中,它从来没有真正返回被点击的元素,它通常返回树上某处元素的主要父级。
使用 MSHTML 还有另一种方法来实现这一目标吗?
我也尝试过使用 WIN API GetCursorPos 但是我不知道如何处理这个位置,我不知道如何将其转换为实际元素。
编辑:我还想到了一个有趣的想法。 当我需要知道有光标的元素时,我在整个文档上设置了 mouseDown 或 click 事件。 然后触发我自己的点击并捕获事件。 在事件的 IHTMLEventObj 中是一个 FromElement,我希望它会告诉我光标在哪里。 似乎 mouseDown 和 click 事件总是没什么。 对我来说,至少这个对象仅用于例如鼠标悬停事件。
以下是我选择至少一个角色时的内容。
Private Function GetHTMLSelection(ByVal aDoc As IHTMLDocument2, ByRef htmlText As String) As Integer
Dim sel As IHTMLSelectionObject = Nothing
Dim selectionRange As IHTMLTxtRange = Nothing
Dim rangeParent As IHTMLElement4 = Nothing
Dim duplicateRange As IHTMLTxtRange = Nothing
Dim i As Integer
Dim x As Integer
Dim found As Boolean
Try
'get a selection
sel = TryCast(aDoc.selection, IHTMLSelectionObject)
If sel Is Nothing Then
Return -1
End If
'the range of the selection.
selectionRange = TryCast(sel.createRange, IHTMLTxtRange)
If selectionRange Is Nothing Then
Return -1
End If
'the the parent element of the range.
rangeParent = TryCast(selectionRange.parentElement, IHTMLElement4)
'duplicate our range so we can manipulate it.
duplicateRange = TryCast(selectionRange.duplicate, IHTMLTxtRange)
'make the dulicate range the whole element text.
duplicateRange.moveToElementText(rangeParent)
'get the length of the whole text
i = duplicateRange.text.Length
For x = 1 To i
duplicateRange.moveStart("character", 1)
If duplicateRange.compareEndPoints("StartToStart", selectionRange) = 0 Then
found = True
Exit For
End If
Next
If found Then
Debug.Print("Position is: " + x.ToString)
htmlText = duplicateRange.text
Return x
Else
Return -1
End If
Catch ex As Exception
Return -1
Finally
End Try
End Function