简体   繁体   中英

Select text only one line at a time from group of divs

Backdrop

I am trying to select the text inside of one div element at a time from a group of div elements and getting its start and end indices.

I am using the mouseup event to capture the selection of the text by the user.


Current situation

More than one div element is being selected at a time like in the below attached screenshot.

在此处输入图片说明


Expected result

If one div element is selected actively the user should be able to only select that div element after lifting the mouse.

在此处输入图片说明

Like in Google's DialogFlow portal, the user can only select one sentence at one time. For selecting the next sentence he should go to the next row to select it which is illustrated in the below screenshot.

在此处输入图片说明

This is a part of the application stackblitz link which I'm trying to make, which contains as how to reproduce the issue and give a solution.

I am unable to think of ways of how to acheive this, any help will be greatly appreciated.


You could set the CSS property user-select to none on the container of the lines which will prevent text selection altogether, and then on mouse down, enable text selection just on one line.

Resetting the user-select property is a little tricky because it will immediately remove a selection, so you actually have to remember which line was selected and reset it on the next mouse down event.

 let lastTarget; function handleMouseDown(event) { let target = event.target; if (lastTarget) { lastTarget.style.userSelect = ''; } if (target.tagName === 'SPAN') { target = target.parentElement; } target.style.userSelect = 'text'; document.onmouseup = function () { lastTarget = target; document.onmouseup = null; } } container.addEventListener('mousedown', handleMouseDown);
 #container { user-select: none; } #container > div > span { cursor: text; }
 <div id="container"> <div><span>If one div element is selected actively the user should be able to only select that div element after lifting the mouse.</span></div> <div><span>If one div element is selected actively the user should be able to only select that div element after lifting the mouse.</span></div> <div><span>If one div element is selected actively the user should be able to only select that div element after lifting the mouse.</span></div> <div><span>If one div element is selected actively the user should be able to only select that div element after lifting the mouse.</span></div> </div>

如果 div 中的文本永远不会相等,则执行 div 的文本 indexOf(selection) 如果选择了多个 div 中的文本,它将返回 false。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM