简体   繁体   English

使用鼠标光标位置作为CoffeeScript / JavaScript中的范围起点

[英]Using mouse cursor position as a range starting point in CoffeeScript/JavaScript

As the title states, I would like to use my cursor's position as the start point to a range. 如标题所示,我想将光标的位置用作范围的起点。

Right now have simple sample like this 现在有这样的简单样本

<html>
  .
  .
   <p>The quick brown fox jumps over the lazy dog</p>
  .
  .
</html>

On the CS/JS side of things I have event listen set to mouse move that attempts to print out the offset for the cursor position, however I am not using the correct method and end up getting either undefined or no method error s. 在CS / JS方面,我将事件侦听设置为鼠标移动,尝试打印出光标位置的偏移量,但是我没有使用正确的方法,最终得到undefinedno method error s。

Again, really simple CS for the time being since I really just wanted to test it out. 再说一遍,因为我真的只想测试一下,所以暂时是非常简单的CS。

$(document).ready ->

  $(document).mousemove ->
    target = event.target
    console.log("#{target.offset()}") // also tried .rangeOffset .offset

Ideally I would like something that I can input into a range.setStart() function. 理想情况下,我希望可以输入到range.setStart()函数中。

For example, if I was to be moused over the f in fox I would want the offset to be return as 16 so that I may then set the start of the range like so range.setStart(target,16) . 例如,如果要将鼠标悬停在f in fox中,我希望将偏移量返回为16,以便随后可以像range.setStart(target,16)这样设置范围的起点。

Any help setting me in the right direction would be greatly appreciated. 任何帮助我朝正确方向发展的帮助将不胜感激。

edit: After typing this up and submitting it I realized how silly it was to expect the element to give me back offset information. 编辑:键入并提交后,我意识到期望元素向我提供补偿信息是多么愚蠢。 I am terribly lost, please guide me. 我非常迷路,请指导我。

After much googling and many hours of troubleshooting I finally came up with a solution that works for my purposes. 经过大量的搜索和大量的故障排除之后,我终于想出了一种适用于我的目的的解决方案。

The function document.caretPositionFromPoint() or for Webkit document.caretRangeFromPoint() takes X and Y coordinates from an event and returns a caret position that I can then use to create the start point of my range with. 函数document.caretPositionFromPoint()或Webkit的document.caretRangeFromPoint()函数从事件中获取X和Y坐标,并返回插入符位置,然后可以使用该位置创建范围的起点。

$(document).ready ->

  setRange = (event) ->
      if document.caretPositionFromPoint
        #for Firefox
      else if document.caretRangeFromPoint
        range = document.caretRangeFromPoint(event.pageX, event.pageY)
        targetNode = range.startContainer
        offset = range.startOffset
        range.setStart(targetNode, offset)
        range.setEnd(targetNode, 10) #just to test

        sel = window.getSelection()
        sel.removeAllRanges()
        sel.addRange(range)

    element = document.getElementById("content")
    element.addEventListener('mousemove', setRange, true) #eventlistener instead of .mousemove for event bubbling

You should be using pageX or pageY, like this 您应该像这样使用pageX或pageY

 $(document).ready -> $(document).mousemove (e) -> console.log("#{e.pageX}") console.log("#{e.pageY}") 

If you need to get the position relative to a div for example 例如,如果您需要获得相对于div的位置

 $(document).ready -> $(document).mousemove (e) -> console.log("#{e.pageX - $('#divID').offset().left}") console.log("#{e.pageY - $('#divID').offset().top}") 

Applied to your case, it would give you something like this 应用于您的案例,它将为您提供类似的信息

$(document).ready ->
  // set your container
  container = $('span')

  // define a replacement text string
  replacement_container_text = ''
  // iterate over each character inside your container
  $(container.text().split('')).each (i, char) ->
    // put it inside a span and add it to your replacement text string
    replacement_container_text += '<span>' + char + '</span>'

  // set the replacement text string as the html content of your container
  // this replaces the original text with the initial text with each 
  // character wrapped into a span 
  // (which can then be caught as targets for your mousemove events)
  container.html(replacement_container_text)   

And moving your mouse over the paragraph containing your text will give you your mouse position inside the paragraph 将鼠标移到包含文本的段落上将使您在段落内的鼠标位置

see it working here http://jsfiddle.net/zXnk9/ 看到它在这里工作http://jsfiddle.net/zXnk9/


EDIT 编辑

If you need to get the index of the character you are hovering you could use a trick like so: 如果需要获取要悬停的字符的索引,可以使用以下技巧:

Wrap your text inside a container that is exactly the width of your text 将文字包裹在与文字宽度完全相同的容器中

 <span>The quick brown fox jumps over the lazy dog</span> 

And then make the following calculation 然后进行以下计算

 $(document).ready -> // define the container for the text you are intersted in container = $('span') // on mouseover container.mouseover (e) -> // get container width container_width = container.width() // compute the avg character width base on the container width and the number of characters contained in your text. // (If you have some complex formatting inside your container, you would have to adjust this calculation.) char_width = p_width / container.text().length // get the position of your mouse inside position_inside = e.pageX - container.offset().left // define the index of the character you are interested in char_index = Math.floor(position_inside / char_width) - 1 // use it as you wish // print it for example console.log("#{char_index}") 

You can check it working here. 您可以在这里检查它的工作情况。 I've set the event to click so that you can try it precisely on the f of fox, it returns 16. http://jsfiddle.net/zXnk9/1/ 我将事件设置为单击,以便您可以在f f上精确地尝试它,它会返回16。http: //jsfiddle.net/zXnk9/1/

EDIT 2: for a reliable way of doing what you are trying to do 编辑2:一种可靠的方式来做您想做的事情

When loading the document, put every character inside the container into an html node, like this 加载文档时,将容器内的每个字符放入html节点,如下所示

 $(document).ready -> // set your container container = $('span') // define a replacement text string replacement_container_text = '' // iterate over each character inside your container $(container.text().split('')).each (i, char) -> // put it inside a span and add it to your replacement text string replacement_container_text += '<span>' + char + '</span>' // set the replacement text string as the html content of your container // this replaces the original text with the initial text with each // character wrapped into a span // (which can then be caught as targets for your mousemove events) container.html(replacement_container_text) 

Then you can just get the index of the character on which your mouse is positionned with the following 然后,您可以使用以下命令获取将鼠标置于其上的字符的索引

 container.mousemove (e) -> range_start = container.children('span').index $(e.target) console.log(range_start) 

This will work with multi line containers, with paragraphs, etc. 这将适用于多行容器,段落等。

See working example http://jsfiddle.net/2TBFV/ 参见工作示例http://jsfiddle.net/2TBFV/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM