我在这里使用超链接和超链接的点击事件我想要使用java脚本在文本框内复制所选文本(我使用鼠标指针或突出显示的文本选择)我只希望在文本框中选择文本我从鼠标指针中选择或突出显示的文本框。我的java脚本正在工作,但它复制了div的全文
<li><a href="#" onclick="JAVASCRIPT:return Edit();">Candidate Name</a> </li>
<script type="text/javascript">
function Edit() {
alert("hiii");
document.getElementById('<%=txtbox.ClientID%>').value = document.getElementById('<%=divtext.ClientID%>').innerHTML;
return true;
}
</script>
<div>
<asp:TextBox ID="txtbox" runat="server"></asp:TextBox>
</div>
<div id="divtext" runat="server">
TCS Infosys Wipro HP HCL Microsoft Facebook Facebook Facebook
</div>
答案 0 :(得分:0)
试试这个
<!DOCTYPE html>
<html>
<script type="text/javascript">
function getSelectionText(divID) {
var selectedText = "";
if (window.getSelection) {
var sel = window.getSelection();
var div = document.getElementById(divID);
if (sel.rangeCount) {
// Get the selected range
var range = sel.getRangeAt(0);
// Check that the selection is wholly contained within the div text
if (range.commonAncestorContainer == div.firstChild) {
var selectedText = range.toString();
}
}
}
return selectedText;
}
function Edit() {
var selectedText = getSelectionText("divtext")
document.getElementById("txtbox").value = selectedText;
return true;
}
</script>
<body>
<li><a href="#" onclick="JAVASCRIPT:return Edit();">Candidate Name</a> </li>
<div>
<input type="text" ID="txtbox" />
</div>
<div id="divtext">
TCS Infosys Wipro HP HCL Microsoft Facebook Facebook Facebook
</div>
</body>