Get selected text position and place an element next to it

前端 未结 3 1426
挽巷
挽巷 2020-11-27 02:49

tl;dr

The idea is to allow a user to mark any text and see menu pop-up just next to the selection, with possible actions to apply to the selected text.


<
3条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 03:01

    You should probably insert an absolutely position element at the end of the 'range.' This works differently in different browsers, so your best bet might be to sniff.

    And since you asked: this is how the new york times does it in their 'altClickToSearch.js' file:

    function insertButton() {
    
    selectionButton = new Element(
            'span', {
              'className':'nytd_selection_button',
              'id':'nytd_selection_button',
              'title':'Lookup Word',
              'style': 'margin:-20px 0 0 -20px; position:absolute; background:url(http://graphics8.nytimes.com/images/global/word_reference/ref_bubble.png);width:25px;height:29px;cursor:pointer;_background-image: none;filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src="http://graphics8.nytimes.com/images/global/word_reference/ref_bubble.png", sizingMethod="image");'
            }
        )
    
    if (Prototype.Browser.IE) {
      var tmp = new Element('div');
      tmp.appendChild(selectionButton);
      newRange = selection.duplicate();
      newRange.setEndPoint( "StartToEnd", selection);
      newRange.pasteHTML(tmp.innerHTML);
      selectionButton = $('nytd_selection_button');
    }
    else {
      var range = selection.getRangeAt(0);
      newRange = document.createRange();
      newRange.setStart(selection.focusNode, range.endOffset);
      newRange.insertNode(selectionButton);
    }
    }
    

提交回复
热议问题