Ir ao conteúdo
  • Cadastre-se

Posição do cursor em campo textarea com javascript


kleber-caetano

Posts recomendados

Olá Sr(s) ,

Tenho um script ( html + javascript ) para editar programas.

Este script calcula a posiçõa do cursor ( do campo texto area ) em linha x coluna.

As seguintes funções implementam esta posição :

function storePosition(textBox) {
var caretPos = document.selection.createRange();
var boundingTop = (caretPos.offsetTop + textBox.scrollTop) - textBox.__boundingTop;
var boundingLeft = (caretPos.offsetLeft + textBox.scrollLeft) - textBox.__boundingLeft;

textBox.__Line = (boundingTop / textBox.__boundingHeight) + 1;
textBox.__Column = (boundingLeft / textBox.__boundingWidth) + 1;
}
function updatePosition(textBox) {
storePosition(textBox);
document.forms[0].txtLine.value = textBox.__Line;
document.forms[0].txtColumn.value = textBox.__Column;
}

Esta função funciona no meu PC que tem uma resolução de tela 1024 x 768 entretanto

quando executo pelo notebook ( com resolução maior ) os valores calculado da linha e coluna

estão fracionados.

Tentei utilizar Math.round e não deu certo pois este método arredonda para baixo / cima.

Alguém sabe como resolver isto ou seja uma solução genérica ?

Agradeço a atenção dispensada.

kleber

Nota - Peguei este script na internet como exemplo.


<html>
<head>
<script language="JavaScript" type="text/javascript">
<!--
function initPosition(textBox) {
var storedValue = textBox.value;
textBox.value = "";
textBox.select();
var caretPos = document.selection.createRange();
textBox.__boundingTop = caretPos.boundingTop;
textBox.__boundingLeft = caretPos.boundingLeft;
textBox.value = " ";
textBox.select();
caretPos = document.selection.createRange();
textBox.__boundingWidth = caretPos.boundingWidth;
textBox.__boundingHeight = caretPos.boundingHeight;
textBox.value = storedValue;
}
function storePosition(textBox) {
var caretPos = document.selection.createRange();
var boundingTop = (caretPos.offsetTop + textBox.scrollTop) - textBox.__boundingTop;
var boundingLeft = (caretPos.offsetLeft + textBox.scrollLeft) - textBox.__boundingLeft;

textBox.__Line = (boundingTop / textBox.__boundingHeight) + 1;
textBox.__Column = (boundingLeft / textBox.__boundingWidth) + 1;
}
function updatePosition(textBox) {
storePosition(textBox);
document.forms[0].txtLine.value = textBox.__Line;
document.forms[0].txtColumn.value = textBox.__Column;
}
//-->
</script>
<style type="text/css">
body, td, tg, input, select {
font-family: Verdana;
font-size: 10px;
}
</style>
</head>
<body onload="initPosition(document.forms[0].txtLayoutViewer)">
<form>
<table cellspacing="0" cellpadding="3">
<tr>
<td colspan="3">
Change Font Size
<select onchange="this.form.txtLayoutViewer.style.fontSize = this.options[this.selectedIndex].value; initPosition(this.form.txtLayoutViewer);">
<option value="10">10px</option>
<option value="12">12px</option>
<option value="14">14px</option>
<option value="16">16px</option>
<option value="18">18px</option>
<option value="20">20px</option>
<option value="24">24px</option>
<option value="36">36px</option>
</select>
</td>
</tr>
<tr>
<td colspan="3">
<textarea name="txtLayoutViewer"
onmouseup="updatePosition(this)"
onmousedown="updatePosition(this)"
onkeyup="updatePosition(this)"
onkeydown="updatePosition(this)"
onfocus="updatePosition(this)"
rows="15"
cols="75">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec ornare aliquam quam. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos hymenaeos. Pellentesque et quam in dui consequat tempor. Etiam lorem lectus, sollicitudin laoreet, tincidunt nec, pharetra in, magna. Mauris accumsan velit et augue. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</textarea></td>
</tr>
<tr>
<td width="70%">
 </td>
<td width="10%">
Line <input type="text" name="txtLine" style="width: 25px" readonly></td>
<td width="20%">
Column <input type="text" name="txtColumn" style="width: 25px" readonly></td>
</tr>
</table>
</form>
</body>
</html>

Complementando este assunto , realizei vários testes alternando valores das variáveis font-family: xxxxx; font-size: xxx px/pt.

Pude constatar que quando definí valores para estas variáveis , no meu PC , o valor calculado ficou fracionado para linha e coluna.

Nota - Quando omito estes valores nestas variáveis , o valor calculado está correto ( no PC ).

Acredito que o valor default do PC seja o correto para funcionar pois é provável que no meu notebbok o default seja outro.

No meu PC está instalado o windows 2003 server e é um computador mais antigo ( explorer 8 ).

No notebook está instalado o windows 7 ( explorer 11 ).

Alguém sabe qual é o default do explorer 8 para as variáveis font-family: xxxxx; font-size: xxx px/pt ?

Mais uma vez agradeço a atenção ,

Link para o comentário
Compartilhar em outros sites

Eu imaginei agora você usar as propriedades "selectionStart" e/ou "selectionEnd" do textarea para saber em qual carecter está o cursor, ex:

var pos = textarea.selectionStart;

depois você fazer um loop no value do text area contando as colunas até a posição, a cada quebra de linha você zerava o contador da coluna e incrementava o da linha.

mas nesse caso vai ter problema se o textarea estiver quebrando de linha automaticamente.

Link para o comentário
Compartilhar em outros sites

Olá andersondanilo ,

Agradeço sua atenção em responder.

Meu conhecimento em javascript é modesto.

Poderia , por gentileza , me mostrar como codificar sua sugestão para que eu possa implementá-la e testá-la.

Nota - O valor default o explorer ( 8 e 11 ) é font-family:Courier New;font-size:10pt;

Testei no explorer 11 com font-size:11pt/15px e ficou muito próximo porém

fracionou.

Link para o comentário
Compartilhar em outros sites

Consegui calcular linha e coluna conforme sugerido pelo Anderson porém ficou muito lento.

Segue a função :

Chamei com => getPosCursor(document.editor.texto);


function getPosCursor(element) {
var value = 0; var linha = 1; var coluna = 1;
if (typeof(element.selectionStart) != "undefined") {
value = element.selectionStart;
}
else if (document.selection) {
var range = document.selection.createRange();
var storedRange = range.duplicate();
storedRange.moveToElementText(element);
storedRange.setEndPoint("EndToEnd", range);
value = storedRange.text.length - range.text.length;
}
for (var i = 0; i < value; i++) {
if (element.value.charAt(i) == "\n") {
linha = linha + 1;
coluna = 1;
} else {
coluna = coluna + 1;
}
}
document.forms[0].txtLine.value = linha;
document.forms[0].txtColumn.value = coluna;
}

Link para o comentário
Compartilhar em outros sites

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...