首页 > 解决方案 > 我怎么称呼选择事件?选择事件在 jquery 中不起作用

问题描述

这是我的代码,当我调用 onselect 事件时它不起作用。当我在输入标签中调用它时,我如何调用它,当我在输入标签中调用它时,我需要在选择 peragraph 文本时调用它。谢谢

<!DOCTYPE html>
    <html>
    <head>
    <meta charset="utf-8">
    <title></title>
    <style>
    p {
    color: blue;
    }
    div {
    color: red;
    }
    </style>
    <script src="https://code.jquery.com/jquery-3.5.0.js"></script>

    </head>
    <body>

    <div>
      <h1>Attach tooltips to text selection</h1>
      <p>
        You can also try to select a text, then select something else, and see the tooltip automatically update to being properly positioned.<br />
        If you scroll this text while the tooltip is visible, you'll notice how it will automatically flip to stay between the viewport.
      </p>
      <div></div>
      <hr />
      
     
    </div>
    
    <script>
        $( "p" ).select(function() {
      alert('hye');
    });
    
    </script>
    </body>
    </html>

标签: javascriptjquery

解决方案


没有select事件p。你可以利用mouseup事件。

例子。

$(function () {
  $("p").bind('mouseup', function (e) {
    var selection;
    if (window.getSelection) {
      selection = window.getSelection();
    } else if (document.selection) {
      selection = document.selection.createRange();
    }
    selection.toString() !== '' && alert('"' + selection.toString() + '" was selected at ' + e.pageX + '/' + e.pageY);
  });
});
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<div>
  <h1>Attach tooltips to text selection</h1>
  <p>
    You can also try to select a text, then select something else, and see the tooltip automatically update to being
    properly positioned.<br />
    If you scroll this text while the tooltip is visible, you'll notice how it will automatically flip to stay between
    the viewport.
  </p>
  <div></div>
  <hr />


</div>


推荐阅读