如何捕捉文字选择上的事件 [英] How to capture event on text selection

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

问题描述

我正在编写一个JavaScript脚本来执行文本选择操作:

HTML

 < div class =text> 
Lorem Ipsum只是印刷和排版行业的虚拟文本。 Lorem
自16世纪以来,Ipsum一直是业界标准的虚拟文本,当时一台未知的打印机采用了
类型的厨房,并将其制作成样本书。它不仅存活了五个世纪,而且还实现了电子排版的飞跃,基本保持不变。它在20世纪60年代推出,其中含有Lorem Ipsum段落的Letraset表格,以及最近的桌面出版软件,如Aldus
PageMaker,包括Lorem Ipsum版本。
< / div>

JavaScript
< pre $ //在鼠标放在具有类.text类的html元素上时触发事件$ b $(。text)。on(mousedown,function(){
//触发事件,当鼠标向上或者文本选择或空白时
$(this).one(mouseup,function(){
//获取选定文本
var $ textSelection = window.getSelection()。toString();
//检查文本是否被选中
if($ textSelection.length> 0){
// alert($ textSelection。 (您已选择:+ $ textSelection);
}
});
});


解决方案


$ b $

  $(this).one(mouseup,function(){

这应该是

  $(this).on(mouseup ,function(){

现在可以工作吗?


I am writing a JavaScript script to perform any action on text selection:

HTML

<div class="text">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem 
Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of
type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release 
of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus
PageMaker including versions of Lorem Ipsum.
</div>

JavaScript

//Trigger event when mouse down on html element having class ".text"
$(".text").on("mousedown", function () {
    //trigger event when mouse up either with text selection or blank
    $(this).one("mouseup", function () {        
       //get selected text
        var $textSelection = window.getSelection().toString();
        //check if text selected or not
        if ( $textSelection.length > 0 ){
            //alert( $textSelection.length )
            alert("You have selected: "+$textSelection );
        }
    });
});

解决方案

you got typo there...

$(this).one("mouseup", function () {

this should be

$(this).on("mouseup", function () { 

does it work now ?

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

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