บางทีคุณอาจต้องเลือกช่วงนอกเหนือจากตำแหน่งเคอร์เซอร์ นี่คือฟังก์ชั่นที่เรียบง่ายคุณไม่จำเป็นต้องมี jQuery:
function caretPosition(input) {
var start = input[0].selectionStart,
end = input[0].selectionEnd,
diff = end - start;
if (start >= 0 && start == end) {
// do cursor position actions, example:
console.log('Cursor Position: ' + start);
} else if (start >= 0) {
// do ranged select actions, example:
console.log('Cursor Position: ' + start + ' to ' + end + ' (' + diff + ' selected chars)');
}
}
สมมติว่าคุณต้องการเรียกมันบนอินพุตเมื่อใดก็ตามที่มีการเปลี่ยนแปลงหรือเมาส์ย้ายตำแหน่งเคอร์เซอร์ (ในกรณีนี้เรากำลังใช้ jQuery .on()
) สำหรับเหตุผลด้านประสิทธิภาพอาจเป็นความคิดที่ดีที่จะเพิ่มsetTimeout()
หรือสิ่งที่คล้ายกับขีดเส้นใต้_debounce()
ถ้ามีเหตุการณ์เกิดขึ้นใน:
$('input[type="text"]').on('keyup mouseup mouseleave', function() {
caretPosition($(this));
});
นี่คือซอหากคุณต้องการลองใช้: https://jsfiddle.net/Dhaupin/91189tq7/