【问题标题】:select currently focused contenteditable div using jquery使用 jquery 选择当前聚焦的 contenteditable div
【发布时间】:2015-01-31 21:59:40
【问题描述】:

您好,我想选择当前放置光标的父 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
  • 所以只需绑定 onfocus 事件和内部处理程序使用this
  • 等我编辑问题。
  • 那么按钮是DIV的后代吗?如果没有,通过单击按钮,DIV 将失去焦点。通过发布所有相关代码来改进您的问题

标签: javascript jquery html css


【解决方案1】:

所以控制台下面的代码记录了内容可编辑 div 中的文本,该 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');
})

见代码笔:here

【讨论】:

  • 嗨,你能再读一遍这个问题吗,我已经做了一些修改。
  • 更新了答案,你也可以在我的 codepen 上看到一个例子!
【解决方案2】:

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

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

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

【讨论】:

  • 你能再读一遍这个问题吗?我做了一些改变
猜你喜欢
  • 2012-09-28
  • 1970-01-01
  • 2014-06-21
  • 2011-04-17
  • 2010-12-17
  • 2021-11-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多