How to get text from a div from user selection
I have a element with selection DISABLED:
<div id="text" onmousedown="selectionStart();" onmouseup="selectionEnd();">
Stuff Here
</div>
What I want to do is create a div over the text the user is trying to select with the values the user selected inside it (so it looks like it's being highlighted). When the selection is completed, the user can drag this div around without issues.
My code for selectionStart() is basically setting the X position of where the mouse is (and the Y position for drawing the DIV element).
My code for selectionEnd() is getting the final X and Y position and doing a substring of the innerHTML.
The idea would be to get a single character width and continue with that - is that a feasible method?
Update:
I can now get the exact character selection, now all I need to do is make a div (with opacity/transparency) over the selected area. function selectionStart()
{
if (characterWidth == 0)
{
widthCalc = document.getElementById("text");
var storedValue = widthCalc.innerText;
widthCalc.innerText = 'X';
var range = document.body.createTextRange();
range.moveToElementText(widthCalc);
range.select();
var caretPos = document.selection.createRange();
caretPos.select();
caretPos.findText("X");
characterWidth = caretPos.boundingWidth;
widthCa开发者_如何转开发lc.innerText = storedValue;
}
startPositionX = Math.round((mouseX(event)+5)/characterWidth);
startPositionY = mouseY(event);
}
function selectionEnd()
{
endPositionX = Math.round((mouseX(event)+5)/characterWidth);
endPositionY = mouseY(event);
var myRulerText = document.getElementById("text");
newSquare = document.createElement('div');
newSquare.setAttribute('id', 'newSquare')
newSquare.innerText = myRulerText.innerText;
if ((startPositionX - endPositionX) > 0)
{
transferBox = startPositionX;
startPositionX = endPositionX;
endPositionX = transferBox;
}
newSquare.innerText = newSquare.innerText.substring(startPositionX-2,endPositionX-1);
newSquare.style.left = 50;
newSquare.style.top = 100;
alert(newSquare.innerText);
}
Here's a Great Tut for selecting the text
http://davidwalsh.name/text-selection-ajax
精彩评论