繁体   English   中英

使用jquery选择当前关注的contenteditable div

[英]select currently focused contenteditable div using jquery

嗨我想在一个可信的div中选择当前放置的光标的父div。

过程是,页面中有多个contenteditable div。 我想选择插入符/光标当前所在的div。 所以使用jquery我可以改变CSS。

以下是我的div的html代码:

     <button id="changer">change color</button>
     <div id="container">
          <div class="section" contenteditable="true">
          <p>this is my editable paragraph</p>
      </div>

      <div class="section" contenteditable="true">
         <p>this is my editable paragraph 2</p>
      </div>
    </div>

以下是我到目前为止的jquery代码: -

        $('#changer').click(function(){
             document.activeElement.css({'background':'black'}); 
        });

但这给了我错误: - Uncaught TypeError: undefined is not a function

编辑:-

该过程是当用户单击按钮时,将出现调色板灯箱。 点击调色板上的任何颜色。 jquery将选择目前专注的contenteditable div。 并改变CSS。 我想知道如何使用jquery选择当前专注的contenteditable div。

所以控制台下面的代码会将文本记录在聚焦的contenteditable div中。 如果你在事件处理程序中写$(this)它将引用当前div聚焦

$('[contenteditable="true"]').focus(function(){
  console.log($(this).text()); // for example, do whatever you please here
  // you said you want to find the parent div of the element focused
  var $parent = $(this).parent();
  // now $parent is a reference of the parent div of the focused element
});

棘手的是,当用户点击按钮时,contenteditable不再是焦点。 所以让我们创建一个变量来存储我们最后focused contenteditable div ,当用户单击一个按钮时,将对该变量进行更改。

像这样:

var lastFocused;

$('[contenteditable="true"]').focus(function(){
  lastFocused = $(this);
});

$('#changer').on('click', function(){
  console.log(lastFocused);
  lastFocused.css('background-color', 'red');
})

看代码: 这里

所以我认为你被困的是如何获得专注的div[contenteditable]

这个想法是在focus事件触发时存储项目。

$(function() {
    var $focus_item = null;
    $('[contenteditable]').focus(function() {
        $focus_item = $(this);
    });
    $('#changer').click(function(){
         $focus_item.css({'background':'black'}); 
    });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM