contenteditable on doubleclick

前端 未结 3 1553
我寻月下人不归
我寻月下人不归 2021-01-11 19:44

I\'ve got a p tag with some text, and I\'m trying to make it contenteditable but only on doubleclick. How can I prevent browser from placing the cu

相关标签:
3条回答
  • 2021-01-11 20:15

    You could make the text unselectable as in How to disable text selection using jQuery? :

    var p = $('p');
    
    p.attr('unselectable', 'on')
        .css('user-select', 'none')
        .on('selectstart', false);
    
    p.dblclick(function (e) {
        p.css("cursor", "text")
            .attr('contenteditable', true)
            .attr('unselectable', 'off')
            .css('user-select', 'inherit')
            .off('selectstart', false)
            .focus();
    
    });
    
    p.focusout(function () {
        p.css("cursor", "default")
            .attr('unselectable', 'on')
            .attr('contenteditable', false)
            .css('user-select', 'none')
            .on('selectstart', false);
    });
    
    0 讨论(0)
  • 2021-01-11 20:20

    Here is a solution which works for me:

    <script>
    function listenForDoubleClick(element) {
      element.contentEditable = true;
      setTimeout(function() {
        if (document.activeElement !== element) {
          element.contentEditable = false;
        }
      }, 300);
    }
    </script>
    
    <p onclick="listenForDoubleClick(this);" onblur="this.contentEditable=false;">Double-click the text to begin editing.</p>
    

    Here is a working fiddle: https://jsfiddle.net/dtL3xzfb/

    It uses a timeout event to check if the text has been selected within a certain period of time (300ms), if the text is not selected (by a second click) it will set content editable to false again: The content editable parameter is set to true after the first click so text will be selected when you click for a second time.

    0 讨论(0)
  • 2021-01-11 20:28

    try this here a working fiddle

     <p ondblclick="this.contentEditable=true;this.className='inEdit';" onblur="this.contentEditable=false;this.className='';" contenteditable="false" class="">This paragraph uses some simple script to be editable. Double-click the text to begin editing.</p>
    
    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题