gpt4 book ai didi

javascript - 在文本区域的光标位置显示 DIV

转载 作者:行者123 更新时间:2023-12-02 10:14:08 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How do I get the (x, y) pixel coordinates of the caret in text boxes?

(2 个回答)


7年前关闭。




对于我的一个项目,我很想为特定的文本区域提供自动完成功能。类似于智能感知/全能的工作方式。然而,为此我必须找出绝对光标位置,以便我知道 DIV 应该出现在哪里。

事实证明:这是(几乎我希望)不可能实现的。有没有人有一些巧妙的想法如何解决这个问题?

最佳答案

我的 Hacky 实验第 2 版

这个新版本适用于任何字体,可以按需调整,任何文本区域大小。

在注意到你们中的一些人仍在努力让它发挥作用之后,我决定尝试一种新方法。这次我的结果要好得多 - 至少在 linux 上的谷歌浏览器上是这样。我不再有可用的 Windows PC,所以我只能在 Ubuntu 上的 chrome/firefox 上进行测试。我的结果在 Chrome 上 100% 一致,假设在 Firefox 上大约 70 - 80%,但我不认为找到不一致会非常困难。

这个新版本依赖于 Canvas 对象。在我的 example ,我实际上展示了那个非常 Canvas - 只是为了让您可以看到它的实际效果,但是使用隐藏的 Canvas 对象可以很容易地完成。

这肯定是一个黑客行为,我提前为我相当困惑的代码道歉。至少,在谷歌浏览器中,无论我将其设置为什么字体或 textarea 的大小,它都能始终如一地工作。我用过 Sam Saffron的示例显示光标坐标(灰色背景 div)。我还添加了一个“随机化”链接,因此您可以看到它以不同的字体/texarea 大小和样式工作,并实时观察光标位置的更新。我建议看 the full page demo所以你可以更好地看到同伴 Canvas 一起玩。

我将总结它是如何工作的......

潜在的想法是我们试图在 Canvas 上尽可能接近地重绘文本区域。由于浏览器对 texarea 和 texarea 使用相同的字体引擎,我们可以使用 canvas 的字体测量功能来找出东西在哪里。从那里,我们可以使用我们可用的 Canvas 方法来计算我们的坐标。

首先,我们调整 Canvas 以匹配 textarea 的尺寸。这完全是出于视觉目的,因为 Canvas 大小并没有真正影响我们的结果。由于 Canvas 实际上并没有提供自动换行的方法,我不得不想出一种方法(一起偷/借/munge)分解行以尽可能匹配 textarea 的方法。在这里,您可能会发现需要进行最多的跨浏览器调整。

自动换行后,其他一切都是基本的数学。我们将这些行拆分成一个数组来模拟自动换行,现在我们想遍历这些行并一直向下直到我们当前选择的结束点。为了做到这一点,我们只是计算字符,一旦我们超过 selection.end ,我们知道我们已经走得够远了。将直到该点的行数与行高相乘,得到 y协调。
x坐标非常相似,除了我们使用的是 context.measureText .只要我们打印出正确数量的字符,这就会给我们绘制到 Canvas 的线的宽度,它恰好在写出的最后一个字符之后结束,这是当前selection.end 之前的字符。位置。

当尝试为其他浏览器调试时,要寻找的是线路没有正确断开的地方。您会在某些地方看到 Canvas 中一行的最后一个单词可能已覆盖在 textarea 上,反之亦然。这与浏览器如何处理自动换行有关。只要您在 Canvas 中进行包装以匹配 textarea,您的光标就应该是正确的。

我将在下面粘贴来源。您应该能够复制和粘贴它,但是如果您这样做了,我要求您下载自己的 jquery-fieldselection 副本,而不是点击我服务器上的副本。

我也加了a new demo以及 a fiddle .

祝你好运!

<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8" />
<title>Tooltip 2</title>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="http://enobrev.info/cursor/js/jquery-fieldselection.js"></script>
<style type="text/css">
form {
float: left;
margin: 20px;
}

#textariffic {
height: 400px;
width: 300px;
font-size: 12px;
font-family: 'Arial';
line-height: 12px;
}

#tip {
width:5px;
height:30px;
background-color: #777;
position: absolute;
z-index:10000
}

#mock-text {
float: left;
margin: 20px;
border: 1px inset #ccc;
}

/* way the hell off screen */
.scrollbar-measure {
width: 100px;
height: 100px;
overflow: scroll;
position: absolute;
top: -9999px;
}

#randomize {
float: left;
display: block;
}
</style>
<script type="text/javascript">
var oCanvas;
var oTextArea;
var $oTextArea;
var iScrollWidth;

$(function() {
iScrollWidth = scrollMeasure();
oCanvas = document.getElementById('mock-text');
oTextArea = document.getElementById('textariffic');
$oTextArea = $(oTextArea);

$oTextArea
.keyup(update)
.mouseup(update)
.scroll(update);

$('#randomize').bind('click', randomize);

update();
});

function randomize() {
var aFonts = ['Arial', 'Arial Black', 'Comic Sans MS', 'Courier New', 'Impact', 'Times New Roman', 'Verdana', 'Webdings'];
var iFont = Math.floor(Math.random() * aFonts.length);
var iWidth = Math.floor(Math.random() * 500) + 300;
var iHeight = Math.floor(Math.random() * 500) + 300;
var iFontSize = Math.floor(Math.random() * 18) + 10;
var iLineHeight = Math.floor(Math.random() * 18) + 10;

var oCSS = {
'font-family': aFonts[iFont],
width: iWidth + 'px',
height: iHeight + 'px',
'font-size': iFontSize + 'px',
'line-height': iLineHeight + 'px'
};

console.log(oCSS);

$oTextArea.css(oCSS);

update();
return false;
}

function showTip(x, y) {
$('#tip').css({
left: x + 'px',
top: y + 'px'
});
}

// https://stackoverflow.com/a/11124580/14651
// https://stackoverflow.com/a/3960916/14651

function wordWrap(oContext, text, maxWidth) {
var aSplit = text.split(' ');
var aLines = [];
var sLine = "";

// Split words by newlines
var aWords = [];
for (var i in aSplit) {
var aWord = aSplit[i].split('\n');
if (aWord.length > 1) {
for (var j in aWord) {
aWords.push(aWord[j]);
aWords.push("\n");
}

aWords.pop();
} else {
aWords.push(aSplit[i]);
}
}

while (aWords.length > 0) {
var sWord = aWords[0];
if (sWord == "\n") {
aLines.push(sLine);
aWords.shift();
sLine = "";
} else {
// Break up work longer than max width
var iItemWidth = oContext.measureText(sWord).width;
if (iItemWidth > maxWidth) {
var sContinuous = '';
var iWidth = 0;
while (iWidth <= maxWidth) {
var sNextLetter = sWord.substring(0, 1);
var iNextWidth = oContext.measureText(sContinuous + sNextLetter).width;
if (iNextWidth <= maxWidth) {
sContinuous += sNextLetter;
sWord = sWord.substring(1);
}
iWidth = iNextWidth;
}
aWords.unshift(sContinuous);
}

// Extra space after word for mozilla and ie
var sWithSpace = (jQuery.browser.mozilla || jQuery.browser.msie) ? ' ' : '';
var iNewLineWidth = oContext.measureText(sLine + sWord + sWithSpace).width;
if (iNewLineWidth <= maxWidth) { // word fits on current line to add it and carry on
sLine += aWords.shift() + " ";
} else {
aLines.push(sLine);
sLine = "";
}

if (aWords.length === 0) {
aLines.push(sLine);
}
}
}
return aLines;
}

// http://davidwalsh.name/detect-scrollbar-width
function scrollMeasure() {
// Create the measurement node
var scrollDiv = document.createElement("div");
scrollDiv.className = "scrollbar-measure";
document.body.appendChild(scrollDiv);

// Get the scrollbar width
var scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;

// Delete the DIV
document.body.removeChild(scrollDiv);

return scrollbarWidth;
}

function update() {
var oPosition = $oTextArea.position();
var sContent = $oTextArea.val();
var oSelection = $oTextArea.getSelection();

oCanvas.width = $oTextArea.width();
oCanvas.height = $oTextArea.height();

var oContext = oCanvas.getContext("2d");
var sFontSize = $oTextArea.css('font-size');
var sLineHeight = $oTextArea.css('line-height');
var fontSize = parseFloat(sFontSize.replace(/[^0-9.]/g, ''));
var lineHeight = parseFloat(sLineHeight.replace(/[^0-9.]/g, ''));
var sFont = [$oTextArea.css('font-weight'), sFontSize + '/' + sLineHeight, $oTextArea.css('font-family')].join(' ');

var iSubtractScrollWidth = oTextArea.clientHeight < oTextArea.scrollHeight ? iScrollWidth : 0;

oContext.save();
oContext.clearRect(0, 0, oCanvas.width, oCanvas.height);
oContext.font = sFont;
var aLines = wordWrap(oContext, sContent, oCanvas.width - iSubtractScrollWidth);

var x = 0;
var y = 0;
var iGoal = oSelection.end;
aLines.forEach(function(sLine, i) {
if (iGoal > 0) {
oContext.fillText(sLine.substring(0, iGoal), 0, (i + 1) * lineHeight);

x = oContext.measureText(sLine.substring(0, iGoal + 1)).width;
y = i * lineHeight - oTextArea.scrollTop;

var iLineLength = sLine.length;
if (iLineLength == 0) {
iLineLength = 1;
}

iGoal -= iLineLength;
} else {
// after
}
});
oContext.restore();

showTip(oPosition.left + x, oPosition.top + y);
}

</script>
</head>
<body>

<a href="#" id="randomize">Randomize</a>

<form id="tipper">
<textarea id="textariffic">Aliquam urna. Nullam augue dolor, tincidunt condimentum, malesuada quis, ultrices at, arcu. Aliquam nunc pede, convallis auctor, sodales eget, aliquam eget, ligula. Proin nisi lacus, scelerisque nec, aliquam vel, dictum mattis, eros. Curabitur et neque. Fusce sollicitudin. Quisque at risus. Suspendisse potenti. Mauris nisi. Sed sed enim nec dui viverra congue. Phasellus velit sapien, porttitor vitae, blandit volutpat, interdum vel, enim. Cras sagittis bibendum neque. Proin eu est. Fusce arcu. Aliquam elit nisi, malesuada eget, dignissim sed, ultricies vel, purus. Maecenas accumsan diam id nisi.

Phasellus et nunc. Vivamus sem felis, dignissim non, lacinia id, accumsan quis, ligula. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed scelerisque nulla sit amet mi. Nulla consequat, elit vitae tempus vulputate, sem libero rhoncus leo, vulputate viverra nulla purus nec turpis. Nam turpis sem, tincidunt non, congue lobortis, fermentum a, ipsum. Nulla facilisi. Aenean facilisis. Maecenas a quam eu nibh lacinia ultricies. Morbi malesuada orci quis tellus.

Sed eu leo. Donec in turpis. Donec non neque nec ante tincidunt posuere. Pellentesque blandit. Ut vehicula vestibulum risus. Maecenas commodo placerat est. Integer massa nunc, luctus at, accumsan non, pulvinar sed, odio. Pellentesque eget libero iaculis dui iaculis vehicula. Curabitur quis nulla vel felis ullamcorper varius. Sed suscipit pulvinar lectus.</textarea>

</form>

<div id="tip"></div>

<canvas id="mock-text"></canvas>
</body>
</html>

错误

我确实记得有一个错误。如果将光标放在一行的第一个字母之前,它会将“位置”显示为上一行的最后一个字母。这与 selection.end 的工作方式有关。我认为寻找那个案例并相应地修复它应该不会太难。

版本 1

把它留在这里,这样你就可以看到进度,而不必翻阅编辑历史。

它并不完美,而且绝对是一种 hack,但我让它在 WinXP IE、FF、Safari、Chrome 和 Opera 上运行良好。

据我所知,无法在任何浏览器上直接找出光标的 x/y。 IE method , mentioned来自 Adam Bellaire很有趣,可惜不能跨浏览器。我认为下一个最好的方法是将字符用作网格。

不幸的是,任何浏览器都没有内置字体度量信息,这意味着等宽字体是唯一具有一致度量的字体类型。此外,没有可靠的方法可以从字体高度中确定字体宽度。起初我尝试使用高度的百分比,效果很好。然后我改变了字体大小,一切都变糟了。

我尝试了一种计算字符宽度的方法,即创建一个临时 textarea 并不断添加字符,直到 scrollHeight(或 scrollWidth)发生变化。这似乎是合理的,但在这条路的一半左右,我意识到我可以只在 textarea 上使用 cols 属性,并认为在这个考验中有足够的 hack 来添加另一个。这意味着您不能通过 css 设置 textarea 的宽度。你必须使用 cols 才能工作。

我遇到的下一个问题是,即使您通过 css 设置字体,浏览器也会以不同的方式报告字体。当你不设置字体时,mozilla 使用 monospace默认情况下,IE 使用 Courier New , 歌剧 "Courier New" (带引号),Safari, 'Lucida Grand' (带单引号)。当您将字体设置为 monospace 时, mozilla 和 ie 拿走你给他们的东西,Safari 显示为 -webkit-monospace和歌剧留在 "Courier New" .

所以现在我们初始化一些变量。确保也在 css 中设置你的行高。 Firefox 报告正确的行高,但 IE 报告“正常”,我没有打扰其他浏览器。我只是在我的 css 中设置了行高并解决了差异。我还没有测试过使用 em 而不是像素。字符高度只是字体大小。也应该在你的 css 中预先设置。

此外,在我们开始放置 Angular 色之前还有一个预设——这真的让我摸不着头脑。对于 ie 和 mozilla,texarea 字符是 < cols,其他的都是 <= 字符。所以 Chrome 可以容纳 50 个字符,但是 mozilla 和 ie 会打破最后一个字。

现在我们要为每一行创建一个第一个字符位置的数组。我们遍历 textarea 中的每个字符。如果它是一个换行符,我们将向我们的行数组添加一个新位置。如果它是一个空格,我们会尝试弄清楚当前的“单词”是否适合我们所在的行,或者它是否会被推到下一行。标点符号算作“词”的一部分。我还没有用制表符测试过,但是有一行可以为制表符添加 4 个字符。

一旦我们有了一个行位置数组,我们就会遍历并尝试找到光标所在的行。我们使用选择的“结束”作为我们的光标。

x = (光标位置 - 光标所在行的第一个字符位置) * 字符宽度

y = ((光标行 + 1) * 行高) - 滚动位置

我正在使用 jquery 1.2.6 , jquery-fieldselection , 和 jquery-dimensions

演示: http://enobrev.info/cursor/

和代码:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tooltip</title>
<script type="text/javascript" src="js/jquery-1.2.6.js"></script>
<script type="text/javascript" src="js/jquery-fieldselection.js"></script>
<script type="text/javascript" src="js/jquery.dimensions.js"></script>
<style type="text/css">
form {
margin: 20px auto;
width: 500px;
}

#textariffic {
height: 400px;
font-size: 12px;
font-family: monospace;
line-height: 15px;
}

#tip {
position: absolute;
z-index: 2;
padding: 20px;
border: 1px solid #000;
background-color: #FFF;
}
</style>
<script type="text/javascript">
$(function() {
$('textarea')
.keyup(update)
.mouseup(update)
.scroll(update);
});

function showTip(x, y) {
y = y + $('#tip').height();

$('#tip').css({
left: x + 'px',
top: y + 'px'
});
}

function update() {
var oPosition = $(this).position();
var sContent = $(this).val();

var bGTE = jQuery.browser.mozilla || jQuery.browser.msie;

if ($(this).css('font-family') == 'monospace' // mozilla
|| $(this).css('font-family') == '-webkit-monospace' // Safari
|| $(this).css('font-family') == '"Courier New"') { // Opera
var lineHeight = $(this).css('line-height').replace(/[^0-9]/g, '');
lineHeight = parseFloat(lineHeight);
var charsPerLine = this.cols;
var charWidth = parseFloat($(this).innerWidth() / charsPerLine);


var iChar = 0;
var iLines = 1;
var sWord = '';

var oSelection = $(this).getSelection();
var aLetters = sContent.split("");
var aLines = [];

for (var w in aLetters) {
if (aLetters[w] == "\n") {
iChar = 0;
aLines.push(w);
sWord = '';
} else if (aLetters[w] == " ") {
var wordLength = parseInt(sWord.length);


if ((bGTE && iChar + wordLength >= charsPerLine)
|| (!bGTE && iChar + wordLength > charsPerLine)) {
iChar = wordLength + 1;
aLines.push(w - wordLength);
} else {
iChar += wordLength + 1; // 1 more char for the space
}

sWord = '';
} else if (aLetters[w] == "\t") {
iChar += 4;
} else {
sWord += aLetters[w];
}
}

var iLine = 1;
for(var i in aLines) {
if (oSelection.end < aLines[i]) {
iLine = parseInt(i) - 1;
break;
}
}

if (iLine > -1) {
var x = parseInt(oSelection.end - aLines[iLine]) * charWidth;
} else {
var x = parseInt(oSelection.end) * charWidth;
}
var y = (iLine + 1) * lineHeight - this.scrollTop; // below line

showTip(oPosition.left + x, oPosition.top + y);
}
}

</script>
</head>
<body>
<form id="tipper">
<textarea id="textariffic" cols="50">
Aliquam urna. Nullam augue dolor, tincidunt condimentum, malesuada quis, ultrices at, arcu. Aliquam nunc pede, convallis auctor, sodales eget, aliquam eget, ligula. Proin nisi lacus, scelerisque nec, aliquam vel, dictum mattis, eros. Curabitur et neque. Fusce sollicitudin. Quisque at risus. Suspendisse potenti. Mauris nisi. Sed sed enim nec dui viverra congue. Phasellus velit sapien, porttitor vitae, blandit volutpat, interdum vel, enim. Cras sagittis bibendum neque. Proin eu est. Fusce arcu. Aliquam elit nisi, malesuada eget, dignissim sed, ultricies vel, purus. Maecenas accumsan diam id nisi.

Phasellus et nunc. Vivamus sem felis, dignissim non, lacinia id, accumsan quis, ligula. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed scelerisque nulla sit amet mi. Nulla consequat, elit vitae tempus vulputate, sem libero rhoncus leo, vulputate viverra nulla purus nec turpis. Nam turpis sem, tincidunt non, congue lobortis, fermentum a, ipsum. Nulla facilisi. Aenean facilisis. Maecenas a quam eu nibh lacinia ultricies. Morbi malesuada orci quis tellus.

Sed eu leo. Donec in turpis. Donec non neque nec ante tincidunt posuere. Pellentesque blandit. Ut vehicula vestibulum risus. Maecenas commodo placerat est. Integer massa nunc, luctus at, accumsan non, pulvinar sed, odio. Pellentesque eget libero iaculis dui iaculis vehicula. Curabitur quis nulla vel felis ullamcorper varius. Sed suscipit pulvinar lectus.
</textarea>

</form>

<p id="tip">Here I Am!!</p>
</body>
</html>

关于javascript - 在文本区域的光标位置显示 DIV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/128342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com