JavaScript mouseover / mousemove cusor postion,无需点击输入文本框

时间:2015-08-24 14:44:28

标签: javascript mouseover mousemove getcomputedstyle

我尝试组合JavaScript机制,通过mouseover和mousemove侦听器自动将用户光标放在输入框内。

我在这里有一个近乎完美的工作示例:http://codepen.io/anon/pen/doxNLm?editors=101

  var current_element = document.getElementById("hover");
  current_element.onmousemove = function showCoords(evt) {

    var form = document.forms.form_coords;
    var parent_id = this.id;
    form.parentId.value = parent_id;
    form.pageXCoords.value = evt.pageX;
    form.pageYCoords.value = evt.pageY;
    form.layerXCoords.value = evt.layerX;
    form.layerYCoords.value = evt.layerY;

    function getTextWidth(text, font) {
      // re-use canvas object for better performance
      var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
      var context = canvas.getContext("2d");
      context.font = font;
      var metrics = context.measureText(text);
      return metrics.width;
    };

    var element_base_browser_styles = window.getDefaultComputedStyle(current_element);
    var total_text_pixal_length = getTextWidth(current_element.value, element_base_browser_styles.fontFamily + " " + element_base_browser_styles.fontSize);

    var add_char_pixal_lengths = 0;

    var myStringArray = current_element.value.split('');
    var arrayLength = myStringArray.length;
    for (var i = 0; i <= arrayLength; i++) {
      var get_char_value = getTextWidth(myStringArray[i], element_base_browser_styles.fontFamily + " " + element_base_browser_styles.fontSize);

      add_char_pixal_lengths = add_char_pixal_lengths + (get_char_value) + 1.311111111111; //every char value is added together. 
     // console.log("Total: " + x);

      if ((add_char_pixal_lengths)> (evt.layerX)) { 
        this.setSelectionRange(i, i);
        add_char_pixal_lengths = 0;
        break;
      }
    }
  }

  current_element.onmouseover = function() {
    this.focus()
  }

我遇到的问题就像地球同步轨道;光标有时偏移几个像素(左或右)。我的计算可能很糟糕,但我不确定画布是否真的是进行测量的最佳方式?还有更好的方法吗?

  1. mousemove listener从e.pageX
  2. 接收元素光标坐标
  3. 使用window.getComputedStyles(input_element)
  4. 的字体样式 来自input_element.text字符串的
  5. arr.split(&#39;&#39;):x = [&#39; a&#39;,&#39; b&#39;,&#39; c&#39 ]
  6. &#39; for loop&#39;数组,生成画布并测量每个字符的宽度
  7. 逐个添加所有字符宽度,直到值大于e.pageX
  8. 设置&#39; for循环&#39;迭代为setSelectionRange(i,i)
  9. 任何有关使这更好的帮助或建议将不胜感激。谢谢!

0 个答案:

没有答案