使用javascript在单击按钮时获取所选文本?

使用javascript在单击按钮时获取所选文本?,javascript,jquery,Javascript,Jquery,基本上,如果用户单击div,我会尝试获取所选文本 代码: 不幸的是,使用上述方法时,单击鼠标时,它首先取消选择文本,然后返回的值为空 我还尝试了event.preventDefault和event.stopproperation,但仍然不起作用。根据我对您问题的理解,我猜您希望在单击按钮时显示所选文本。因此,只需将所选内容保存在hiddenfield中,然后从那里显示,就可以了 $'btnSave'。单击函数{ console.log$hdnValue.val; }; $'.boldTextB

基本上,如果用户单击div,我会尝试获取所选文本

代码:

不幸的是,使用上述方法时,单击鼠标时,它首先取消选择文本,然后返回的值为空


我还尝试了event.preventDefault和event.stopproperation,但仍然不起作用。

根据我对您问题的理解,我猜您希望在单击按钮时显示所选文本。因此,只需将所选内容保存在hiddenfield中,然后从那里显示,就可以了

$'btnSave'。单击函数{ console.log$hdnValue.val; }; $'.boldTextButton'.mouseupfunctionevent{ var SelectionDetails=getSelectionText; $hdnValue.vals选择详细信息; }; 函数getSelectionText{ var text=,startRange=0,endRange=0; 如果window.getSelection{ text=window.getSelection.toString; startRange=window.getSelection.anchorOffset; endRange=window.getSelection.focusOffset; }否则如果document.selection&&document.selection.type!=控件{ text=document.selection.createRange.text; } 返回[text,endRange,startRange]; } 示例文本1 示例文本2 示例文本3 示例文本4示例文本5 示例文本6 示例文本7示例文本8 示例文本9 示例文本10示例文本11
您想在鼠标右键单击时选择文本吗?@turivishal,我想在有人单击div容器/按钮时获取所选文本。您想在单击按钮时显示所选文本吗?这是否回答了您的问题?我认为上述方法需要大量事件处理,例如,如果用户使用ctlr+a,shift+箭头等进行选择,然后使用显示按钮进行打印,您知道更简单的方法吗?NVM,声明了一个全局变量来存储值,有点哑,但只有在执行以下操作时才起作用:让SelectionDetails=getSelectionText;globalSelection=SelectionDetails;然后单击“显示”按钮,可以访问所选内容。我使用了隐藏字段,这应该允许随时获取所选文本。隐藏字段将作为一个全局变量工作,它更可信。
$('.boldTextButton').mouseup(function(event){
    var SelectionDetails = getSelectionText();
    console.log(SelectionDetails);
});

function getSelectionText() {
    var text = "", startRange=0, endRange=0;
    if (window.getSelection) {
        text = window.getSelection().toString();
        startRange = window.getSelection().anchorOffset;
        endRange = window.getSelection().focusOffset;
    } else if (document.selection && document.selection.type != "Control"){
        text = document.selection.createRange().text;
    }

    return [text, endRange, startRange];
}