javascript - 如何在文本区域中的选定文本下方显示一个 div?

标签 javascript jquery css

我有一个场景,我需要在文本区域中显示一个 div(如弹出窗口)选择文本。但是,我使用鼠标按下它,div 的位置有时并不完全在文本下方.

JavaScript:

    function getSel() {
    // obtain the object reference for the textarea>
    var txtarea = document.getElementById("mytextarea");
    // obtain the index of the first selected character
    var start = txtarea.selectionStart;
    // obtain the index of the last selected character
    var finish = txtarea.selectionEnd;
    //obtain all Text
    var allText = txtarea.value;
    // obtain the selected text
    var sel = allText.substring(start, finish);
    sel = sel.replace(/[\S]/g, "*");
    //append te text;
    var newText = allText.substring(0, start) + sel + allText.substring(finish, allText.length);
    txtarea.value = newText;
    $('#newpost').offset({ top: 0, left: 0 }).hide();
}

$(document).ready(function () {
    var position;
    $('#newpost').hide();
    $('#mytextarea').on('select', function (e) {
        var str = $('#mytextarea').val();
        $('#newpost').offset(position).show();
        var txtarea = document.getElementById("mytextarea");
        var start = txtarea.selectionStart;
        var finish = txtarea.selectionEnd;
        $('#newpost div').text('Replace with stars');
    }).on('select', function (e) {
        position = { top: e.pageY+10, left: e.pageX };
    });
    $('#newpost').hide();
});
function closePopUp() {
    $('#newpost').hide();
}

这是我的 plunker链接

这里我的要求是在选择文本时显示一个 div。但是当我使用 on-select 而不是鼠标按下时,div 显示在文本区域下方。

提前致谢。

最佳答案

几天前在this answer我提出了一种方法,当用户选择一些文本时,找到光标位置并在 textarea 上显示一个 div

但是,正如@anub 所提到的,这种方法有效,div 有时不显示在所选文本的正下方,而是向上或向下显示几个像素 - 因为它的位置是根据第一个用户的点击。

经过简短的搜索,我找到了 this post它描述了如何通过创建给定文本区域的临时 div 克隆来找到选定文本在文本区域中的位置。

我从那里采用了 getCursorXY 方法并用它来定位弹出窗口。

试试吧!

function getSel() {
    // obtain the object reference for the textarea>
    var txtarea = document.getElementById("mytextarea");
    // obtain the index of the first selected character
    var start = txtarea.selectionStart;
    // obtain the index of the last selected character
    var finish = txtarea.selectionEnd;
    //obtain all Text
    var allText = txtarea.value;

    // obtain the selected text
    var sel = Array(finish - start + 1).join("*");
    //append te text;
    var newText = allText.substring(0, start) + sel + allText.substring(finish, allText.length);
    txtarea.value = newText;
    
    $('#newpost').offset({top: 0, left: 0}).hide();
}
function closePopUp() {
    $('#newpost').offset({top: 0, left: 0}).hide();
}

$(document).ready(function () {
    closePopUp();
    var newpost = $('#newpost');
    $('#mytextarea').on('select', function (e) {
        var txtarea = document.getElementById("mytextarea");
        var start = txtarea.selectionStart;
        var finish = txtarea.selectionEnd;
        newpost.offset(getCursorXY(txtarea, start, 20)).show();
        newpost.find('div').text(Array(finish - start + 1).join("*"));
    });
});

const getCursorXY = (input, selectionPoint, offset) => {
  const {
    offsetLeft: inputX,
    offsetTop: inputY,
  } = input
  // create a dummy element that will be a clone of our input
  const div = document.createElement('div')
  // get the computed style of the input and clone it onto the dummy element
  const copyStyle = getComputedStyle(input)
  for (const prop of copyStyle) {
    div.style[prop] = copyStyle[prop]
  }
  // we need a character that will replace whitespace when filling our dummy element 
  // if it's a single line <input/>
  const swap = '.'
  const inputValue = input.tagName === 'INPUT' ? input.value.replace(/ /g, swap) : input.value
  // set the div content to that of the textarea up until selection
  const textContent = inputValue.substr(0, selectionPoint)
  // set the text content of the dummy element div
  div.textContent = textContent
  if (input.tagName === 'TEXTAREA') div.style.height = 'auto'
  // if a single line input then the div needs to be single line and not break out like a text area
  if (input.tagName === 'INPUT') div.style.width = 'auto'
  // create a marker element to obtain caret position
  const span = document.createElement('span')
  // give the span the textContent of remaining content so that the recreated dummy element 
  // is as close as possible
  span.textContent = inputValue.substr(selectionPoint) || '.'
  // append the span marker to the div
  div.appendChild(span)
  // append the dummy element to the body
  document.body.appendChild(div)
  // get the marker position, this is the caret position top and left relative to the input
  const { offsetLeft: spanX, offsetTop: spanY } = span
  // lastly, remove that dummy element
  // NOTE:: can comment this out for debugging purposes if you want to see where that span is rendered
  document.body.removeChild(div)
  // return an object with the x and y of the caret. account for input positioning 
  // so that you don't need to wrap the input
  return {
    left: inputX + spanX,
    top: inputY + spanY + offset,
  }
}
#mytextarea {width: 600px; height: 200px; overflow:hidden; position:fixed}
#newpost {
    position:absolute;
    background-color:#ffffdc;
    border:1px solid #DCDCDC;
    border-radius:10px;
    padding-right:5px; 
    width: auto;
    height: 30px;
}
#newpost span {
    cursor:pointer;
    position: absolute;
    top: 0;
    right: 5px;
    font-size: 22px;
}
#newpost div {
    color:#0000ff;
    padding:10px;
    margin-right:10px;
    width: auto;
    cursor:pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
  <head>
  </head>
 <body>
    <textArea id="mytextarea"></textArea>
    <div id="newpost">
        <span onclick="closePopUp();">&#735;</span>
        <div onclick="getSel()"></div>
    </div>
</body>

</html>

关于javascript - 如何在文本区域中的选定文本下方显示一个 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48496292/

相关文章:

javascript - 如何使用我的 spotify api token ?

jquery - 动态 <li> 没有响应

javascript - 将对象作为参数传递给js函数时出现"Expected ]"错误

javascript - 每次输入文本更改时调用函数

javascript - 合并静态文件或并行加载

javascript - 使用 IE 过滤器时不应用悬停样式,无法单击元素

javascript - 重定向到 Node js Express 中的新页面?

javascript - nvd3 删除空点的工具提示内容

jquery - 将 jQuery 从 1.3.2 和 1.4.2 升级到 1.5.1

javascript - JS/jQuery 在页面加载时显示 DIV,在点击时隐藏