【问题标题】:window.getselection is not working in androidwindow.getselection 在android中不起作用
【发布时间】:2012-12-26 05:10:40
【问题描述】:

我是使用 html+javascript+jQuery 的新手。我正在尝试使用 window.getSelection 来获取选定的文本,但这不起作用。 任何人都可以为此提出解决方案。

提前致谢。

【问题讨论】:

    标签: javascript android jquery html


    【解决方案1】:

    试试

    function getSelected() {
    var text = "";
    if (window.getSelection && window.getSelection().toString() && $(window.getSelection()).attr('type') != "Caret") {
        text = window.getSelection();
        return text;
    } else if (document.getSelection && document.getSelection().toString() && $(document.getSelection()).attr('type') != "Caret") {
        text = document.getSelection();
        return text;
    } else {
        var selection = document.selection && document.selection.createRange();
        if (!(typeof selection === "undefined") && selection.text && selection.text.toString()) {
            text = selection.text;
            return text;
        }
    }
    return false;
    }
    

    【讨论】:

      【解决方案2】:

      只需要在 java 脚本中完成你的工作的简单代码行

       //I am using below line of code which works in both android and web browsers.
      
      function getSelectedText() {
          var selection = null;
      
          if (window.getSelection) {
              selection = window.getSelection();
          } else if (typeof document.selection != "undefined") {
              selection = document.selection;
          }
      
          var selectedRange = selection.getRangeAt(0);
      
          console.log(selectedRange.toString());
      }
      

      注意:不要在 post 或任何可运行接口内调用此方法,因为 post 或任何可运行接口会延迟调用此方法(方法调用发生在浏览器选择释放后)。只需像

      一样调用此方法
      webView.loadUrl("javascript:getSelectedText()");
      

      【讨论】:

        【解决方案3】:

        如果您想在文本选择后立即调用函数,可以使用“selectionchange”事件:

        document.addEventListener("selectionchange", handleSelection);
        

        它适用于 android chrome 和 iOS safari。

        【讨论】:

          【解决方案4】:

          我知道这是一个非常古老的问题,但是当我尝试解决相同或类似的问题时,我将其作为第一个搜索结果。我在这里没有找到解决方案,但一段时间后我意识到有时对于手机来说,单击和选择之间应该有一个短暂的超时,以使 getSelection() 正常工作。

          例如取而代之的是:

          document.getElementById("element").addEventListener('click', function (event) {
              window.getSelection().selectAllChildren(this)
          });
          

          你应该像这样使用一些想法:

          document.getElementById("element").addEventListener('click', function (event) {
            setTimeout(function(passedThis) {
              window.getSelection().selectAllChildren(passedThis)
            }, 10, this);
          });
          

          也许它可以为某人节省一些时间。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2013-12-23
            • 2017-09-26
            • 1970-01-01
            • 2015-07-20
            • 1970-01-01
            • 2018-06-18
            • 2021-08-31
            • 2016-02-20
            相关资源
            最近更新 更多