我想知道是否有可能在整個頁面中找到textarea內像素的確切位置。例如,如果我在文本框中鍵入This is text
,我想知道從屏幕左上角到卡羅的像素。以像素爲單位在textarea中查找插入位置
它將以X:200 Y:100的形式出現。這樣我可以定位一個浮動div。這需要在javascript中動態地完成。
謝謝你們
我想知道是否有可能在整個頁面中找到textarea內像素的確切位置。例如,如果我在文本框中鍵入This is text
,我想知道從屏幕左上角到卡羅的像素。以像素爲單位在textarea中查找插入位置
它將以X:200 Y:100的形式出現。這樣我可以定位一個浮動div。這需要在javascript中動態地完成。
謝謝你們
這種「原始代碼」的作品,至少在IE中。
使用代碼,你可以把你的<TEXTAREA>
放在任何你想要的頁面上,<DIV id="db">
會跟着它。即使頁面滾動的位置。您可以修改<DIV>
的位置,方法是更改文字編號d.style...6
-語句。
<body>
<div id="db" style="position:absolute;left:-20px;top:-20px;border:1px solid red;">V</div>
<br><br><br>
<form id="props">
<textarea id="ta" style="width:200px;height:100px;" onkeyup="moveDiv();"></textarea>
</form>
<script>
<!--
var b=document.body;
var d=document.getElementById('db');
var a=document.getElementById('ta');
function moveDiv(){
var sel=document.selection;
var targ=sel.createRange();
d.style.top=a.offsetTop+a.clientTop-d.clientHeight-6;
d.style.left=targ.offsetLeft+b.scrollLeft-6;
return;
}
// -->
</script>
</body>
的<DIV>
的定位不是很準確,但在使用<TEXTAREA>
固定寬度字體時變得更好。
這裏有一個插件,這樣:jQuery caret plugin
該插件與插入符的位置相對於輸入字段中的字符一起工作; OP正在尋找插入符的屏幕(即x,y)位置。 –
難道你不贊成反對嗎?請解釋! –
恩,downvote是有幾個原因的,但請不要親自採取 - 如果答案得到肯定更新,我很快就會撤銷downvote。 A)這是一個只有鏈接的答案,[不鼓勵](http://meta.stackexchange.com/questions/8231),B)插件可以幫助OP的努力,它是目的是在輸入中設置和查找特定字符之間的插入符號,這不是OP在這種情況下的意思。 –
有系統的實現:https://github.com/beviz/jquery-caret-position-getter,它可以獲取textarea的(IEX,y)的插入位置
我已將鏈接更改爲Github。 –
有沒有機會不依賴於jQuery? [使用jQuery 1.9。*的插件時遇到了問題,它可以擺脫'$ .browser'](https://github.com/beviz/jquery-caret-position-getter/issues/5)。 –
這裏是思想的Caret position in pixels in an input type text (not a textarea),Caret position in textarea, in characters from the start和document.getElementById vs jQuery $()一個簡單的組合,以獲取插入符位置的jQuery的一個<input>
元素。它在內部點擊時起作用,但在使用箭頭移動插入符號或打字時不起作用。
<input id="someid">
<span id="faux" style="display:none"></span><br/>
<script>
var inputter = $('#someid')[0];
var faux = $('#faux');
function getCaret(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
$("#someid").click(function(event) {
caretpos = getCaret(inputter);
calcfaux = faux.text($(this).val().substring(0, caretpos));
fauxpos = calcfaux.outerWidth();
$("#getpx").text(fauxpos + " px");
});
</script>
而不是var inputter = document.getElementById('someid')
我們使用var inputter = $('#someid')[0];
這裏是一個FIDDLE。
約'42'小精靈。 – alex
感謝您的澄清好友:P – alex
您可能有興趣[任何數量的這些問題](http://stackoverflow.com/search?q=caret+javascript+position+x+y)。 –