html5 contenteditable如何在单击另一个元素时选择All

时间:2015-05-13 07:09:45

标签: jquery html5 contenteditable selectall

我有一组div,其行为有点像输入框。当用户点击"编辑我的详细信息"按钮,他应该能够编辑这些框。编辑框时,我希望在用户点击框中的任何位置时选择框的当前内容。问题是盒子的标签覆盖了它的一部分,我不知道如何处理实际的盒子,即在要选择的标签下面。

这是一个有问题代码简化版的链接。 https://jsfiddle.net/planxdesign/ddptkykf/2/

这是我的HTML:

<div class="container">
  <div class="row">
    <div class="col-sm-12 col-md-10 col-md-offset-1">
      <div class="row">
        <div class="col-sm-4">
          <div class="input-wrap">
            <div class="heading">
              <i class="fa fa-envelope iconic"></i>Home
            </div>
            <div class="edit2 input">12345</div>
          </div>
        </div>
        <div class="col-sm-4">
          <div class="input-wrap">
            <div class="heading">
              <i class="fa fa-envelope iconic"></i>Home
            </div>
            <div class="edit2 input">12345</div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="row">
    <div class="col-xs-3 col-xs-offset-5 col-sm-2 col-sm-offset-6">
      <button id="edit-user" class="btn btn-default"><i class="fa fa-pencil-square-o icon"></i>Edit My Details</button>
    </div>
  </div>
</div>

我的JS:

var user2= {
  editMyDetailsButton: function()
  {
      // Get the edit button
      $('#edit-user').on('click', function(ev)
         {
           ev.preventDefault();
           user2.editables(); // When click, make it editables
          });
  },
  editables: function()
  {
    var $edits = $('.edit2'); // All those with '.edit'
    $edits.each(function()
      {
        $context = $(this);
        user2.editablesStyle($context); // Make them visibly different
        user2.editableClickListeners($context); // Attach click the listeners
        user2.editableKeyListener($context);    // Attach key listener
      });
  },

  editablesStyle: function($context)
  {
    // Set contenteditable=true
    $context.attr('contenteditable', 'true');
    $('.heading').attr('contenteditable', 'false');
      // Add them class editable
      $context.addClass('editable');
  },

  editableClickListeners: function($context)
  {
    $('.input-wrap').on('click', '.edit2, .heading', function( )
       {
          console.log(this);
         // When the editable field is clicked, select all inside
         document.execCommand('selectAll', false, null);
       });
  }

}

user2.editMyDetailsButton();

1 个答案:

答案 0 :(得分:0)

我认为你应该删除这个点击功能中的标题类:

editableClickListeners: function($context)
  {
    $('.input-wrap').on('click', '.edit2', function() // remove heading class here
       {
          console.log(this);
         // When the editable field is clicked, select all inside
         document.execCommand('selectAll', false, null);
       });
  }

<强> DEMO