1

我有一个功能(仍在开发中),需要在 div 中捕获用户选择的文本(不是文本区域和输入框,因此 .select 不起作用。)。Using .click and selection and range objects works great when the selection is contained within a single element in that div but fails to trigger if the user selection spans multiple elements within the div (like multiple p's).

    $('.relevantDivClass').click(function(){
        console.log('Got here');
        SelObj = window.getSelection();
        Range = SelObj.getRangeAt(0);
        if (SelObj.anchorNode == SelObj.focusNode){
            console.log('executing same node branch');
            string = SelObj.toString();
            console.log(string)
        }
        else{
            console.log('executing multiple node branch');
            //code...
        }
    });

关于如何在这种情况下触发该事件的任何想法?它仍然在relatedDivClass 中,所以我对为什么.click 不会触发感到困惑。

提前致谢!

4

2 回答 2

0

希望使用最新的 jQuery 版本,改用这个:

$(".relevantDivClass").on("click", function() { /* code */ });

于 2012-08-08T00:56:41.413 回答
0

使用.mouseup()而不是.click(). 当跨多个段落突出显示文本时,不会在触发 'mousedown' 的同一元素上触发 'mouseup' 事件——这是 'click' 事件的定义。.click()适用于单个段落,因为您在<p>元素上同时触发了“mousedown”和“mouseup”,并且它会冒泡到其父级,<div>.

工作演示

$(function() {
    $('.relevantDivClass').mouseup( function() {
        alert('Got here');
        SelObj = window.getSelection();
        Range = SelObj.getRangeAt(0);
        if (SelObj.anchorNode == SelObj.focusNode){
            alert('executing same node branch');
            string = SelObj.toString();
            alert(string)
        }
        else{
            alert('executing multiple node branch');
            //code...
        }
    });
});
​
于 2012-08-08T01:13:50.127 回答