您好,我想选择当前放置光标的父级 div 中的 contenteditable 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');
})
参见代码笔:here
关于javascript - 使用 jquery 选择当前聚焦的 contenteditable div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28252161/