Вопрос

I'm losing focus on contentEditable when my menu li option is clicked so when I try to execCommand the selection no longer exists and does not affect the selection. How can I solve this without adding an input?

Updated: ** jsFiddle **

HTML

<div contenteditable=true>
    paragraph1<br/>
    paragraph2<br/>
    paragraph3
</div>
<div contenteditable=true>
    paragraph4<br/>
    paragraph5<br/>
    paragraph6
</div>
<input type=button id=show value=ToggleMenu>
<ul id=submenu>
    <li>p</li>
    <li>h1</li>
    <li>h2</li>
</ul>

Javascript

$("#show").on("click",function(){
    $("#submenu").toggle();
});
$("#submenu").on("click","li",function(){  //when this is clicked, editable div loses focus.
    document.execCommand("formatBlock", false, $(this).text());
    console.log($(this).text(), "was clicked");
});
Это было полезно?

Решение

You could do something like the following:

  • use mousedown instead of click
  • prevent the default event behaviour
  • get the relevant <li>'s content
  • call document.execCommand()

Demo: http://jsfiddle.net/timdown/SNTyY/13/

Code:

var $submenu = $("#submenu");

$("#show").on("click",function(){
    $submenu.toggle();
});

$submenu.mousedown("li",function(e){
    var li = e.target;
    e.preventDefault();
    document.execCommand("formatBlock", false, $(li).text());
});

$submenu.click(function(e) {
    e.preventDefault();
});

Другие советы

One issue with your code is that it is not HTML compliant. For example, the sub menu should be

<ul id = 'submenu'>
  <li>p</li>
  <li>h1</li>
  <li>h2</li>
</ul>

Instead of using li as a selector for your click event, try

$("#submenu").on("click", "li", function(){
   document.execCommand("formatBlock", false, $(this).text());
   alert($(this).text());
});

This throws an alert box on a click event, so you know the click is registering.

Fiddle

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top