选择文字后如何弹出? [英] How to have a popup after selecting text?

查看:99
本文介绍了选择文字后如何弹出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法弄清楚.我有一个div,里面有一些文字.当用户选择它的部分时(完全随意,无论他们想要什么),我希望其中的文本出现一个小的弹出窗口.

I can't seem to figure this out. I have a div with some text in it. When the user selects pieces of it (totally at random, whatever they want), I want a small popup to occur with the text inside of it.

要启动弹出窗口,我可以这样做吗? ...

To initiative the popup, can I just do this? ...

$('#textdiv').click(function() {  

但是我如何只获得选中/突出显示的文本?

But then how do I get only the selected/highlighted text?

推荐答案

jQuery在这里用处不大,因此您将需要纯JS来进行选择抓取(贷记到此页面):

jQuery isn't going to be of much use here, so you'll need pure JS to do the selection grabbing part (credit goes to this page):

function getSelected() {
  if(window.getSelection) { return window.getSelection(); }
  else if(document.getSelection) { return document.getSelection(); }
  else {
    var selection = document.selection && document.selection.createRange();
    if(selection.text) { return selection.text; }
    return false;
  }
  return false;
}

您在使用mouseup处理程序的时候走在正确的轨道上,所以这就是我的工作方式:

You were on the right track with the mouseup handler, so here's what I got working:

$('#test').mouseup(function() {
    var selection = getSelected();

    if (selection) {
        alert(selection);
    }
});

和一个实时演示: http://jsfiddle.net/PQbb7/7/.

这篇关于选择文字后如何弹出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆