如何使用jquery更改按钮单击时关注的contenteditable元素类?

时间:2016-10-08 09:49:56

标签: javascript jquery html contenteditable classname

我正在尝试更改位于contenteditable div

中的元素的类

我目前的代码是:

<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>

点击按钮时,我想将课程.line-height-1替换为另一个,用于当前选定的可编辑div

任何人都可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

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

&#13;
&#13;
var element;
$("div[contenteditable]").focus(function(){
    element = this;
});
$("button").click(function(){
    $(element).focus().find("h1").removeClass("line-height-1").addClass("newClass");
});
&#13;
.line-height-1 { color: red }
.newClass { color: blue }
&#13;
<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>
&#13;
&#13;
&#13;