如何使用 jquery 更改按钮单击时聚焦的 contenteditable 元素的 class?

How to change class of focused contenteditable element on button click using jquery?

我正在尝试更改位于 contenteditable div

中的元素的 class

我当前的代码是:

<button>swap class</button>
<div contenteditable="true">
    <h1 class="line-height-1">Your Headline Here</h1>
</div>    
<div contenteditable="true">
    <h1 class="line-height-1">Your Headline Here</h1>
</div>

我想在单击按钮时将 class .line-height-1 替换为另一个 当前选择的可编辑 div

有人能帮忙吗??

当您点击按钮时,焦点元素会变模糊。您需要将焦点元素存储在变量中并在单击按钮时更改它。单击按钮后使其聚焦。

var element;
$("div[contenteditable]").focus(function(){
    element = this;
});
$("button").click(function(){
    $(element).focus().find("h1").removeClass("line-height-1").addClass("newClass");
});
.line-height-1 { color: red }
.newClass { color: blue }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>swap class</button>
<div contenteditable="true">
  <h1 class="line-height-1">Your Headline Here</h1>
</div>
<div contenteditable="true">
  <h1 class="line-height-1">Your Headline Here</h1>
</div>