我正在尝试结合 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()
}
我遇到的问题就像地球同步轨道;光标有时会偏离几个像素(左或右)。我的计算可能很糟糕,但我不确定帆布真的是最好的测量方法吗?有没有更好的办法?
- mousemove 侦听器从 e.pageX 接收元素光标坐标
- 使用 window.getComputedStyles(input_element) 的字体样式
- arr.split('') 来自 input_element.text 字符串:x = ['a','b','c']
- 'for循环'数组,生成画布并测量每个字符的宽度
- 将所有字符宽度一一相加,直到值大于 e.pageX
- 将“for循环”迭代设置为 setSelectionRange(i, i)
任何有关使其更好的帮助或建议将不胜感激。谢谢!