How to have a popup after selecting text?

前端 未结 5 832
天命终不由人
天命终不由人 2021-02-06 02:12

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

5条回答
  •  心在旅途
    2021-02-06 02:50

    Just updated first answer. Try this

    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;
    }
    /* create sniffer */
    $(document).ready(function() {
    	$('#my-textarea').mouseup(function(event) {
    		var selection = getSelected();
            selection = $.trim(selection);
            if(selection != ''){
            $("span.popup-tag").css("display","block");
            $("span.popup-tag").css("top",event.clientY);
            $("span.popup-tag").css("left",event.clientX);
            $("span.popup-tag").text(selection);
            }else{
            $("span.popup-tag").css("display","none");
            }
    	});
    });
    .popup-tag{
    position:absolute;
    display:none;
    background-color:#785448d4;
    color:white;
    padding:10px;
    font-size:20px;
    font-weight:bold;
    text-decoration:underline;
    cursor:pointer;
    -webkit-filter: drop-shadow(0 1px 10px rgba(113,158,206,0.8));
    }
    
    Select any text :

    see: https://jsfiddle.net/arunmaharana123/kxj9pm40/

提交回复
热议问题