1

我试图使文本区域中的每一行都可点击,光标可以是默认的,或者指针无关紧要。jsfiddle

<textarea rows="10" cols="45">
hello
world
</textarea>​

我想在每行中单击文本时进行 ajax 调用。我可以编写所有的 ajax 功能,我想弄清楚的只是单击文本中的每一行。是否可以使用文本区域或者是否有其他替代方法。

编辑

更准确地说,我<c:forEach items="${}" var=""> <c:out value="${} /></c:forEach>在文本区域内使用。它不完全是带有段落标签的文本。文本是动态的,基于在此页面之前选择的输入

4

4 回答 4

3

您可能想使用 selectionStart 来执行此操作。

这是一个例子。随意定制以供您使用。但这应该让你开始。

<textarea rows="10" cols="45" onkeyup="getLineNumber(this, document.getElementById('lineNo'));" onmouseup="this.onkeyup();"></textarea>
<div id="lineNo"></div>

<script>

    function getLineNumber(textarea, indicator) {

        indicator.innerHTML = textarea.value.substr(0, textarea.selectionStart).split("\n").length;
    }

</script>
于 2012-11-26T23:01:13.980 回答
2

If I understood you correctly, you want to get the text of the line you clicked on. If that is so, then the following works with your example:

$("#mytextArea").on("mouseup", function(eventData) {
    var lineHeight = $(this).css("line-height");
    lineHeight = parseInt(lineHeight.substring(0, lineHeight.length - 2));

    var line = Math.floor(eventData.offsetY / lineHeight);
    alert($(this).val().split("\n")[line]);
});

DEMO - Get Text from clicked line in textarea

The code will take the position the mouse was clicked in within the textarea offsetY and divide it by the applied line-height. Using Math.floor() it will get the line which was clicked and use it as the index element in the array when splitting the lines by "\n".

In addition to make this work I enforced the line-height to be a set px value to allow me to calculate the line clicked.

textarea{
    font-size: 15px;
    line-height: 15px;
}​

Edit - Scrollbars on textarea

Assuming the textarea has a scrollbar, the scrollbar will "distort" the offsetY value and you need to add the current scroll position to it like this:

$("#mytextArea").on("mouseup", function(eventData) {
    var scrollPosition = $(this).scrollTop()
    var lineHeight = $(this).css("line-height");
    lineHeight = parseInt(lineHeight.substring(0, lineHeight.length - 2));

    var line = Math.floor((eventData.offsetY + scrollPosition) / lineHeight);
    alert($(this).val().split("\n")[line]);
});​

DEMO - Get Text from clicked line in textarea with scrollbar

I updated the CSS to a fixed height to get a scrollbar like this:

textarea{
    font-size: 15px;
    line-height: 15px;
    height: 100px;    
}
于 2012-11-26T23:19:12.687 回答
0

您可以在 中获取光标位置textarea,找出其中的文本,然后执行 ajax。话虽如此,将元素(pre, a, input)分开并让它们的每个点击功能触发您想要的 ajax 调用会更容易。

于 2012-11-26T23:00:54.183 回答
0

您可以将每一行放在 ap 标签内并使用 onclick :

<p onclick="myFunction()">Hello</p>
<p onclick="myOtherFunction()">World</p>
于 2012-11-26T23:03:58.790 回答