Jump to content
  • 0

Как вставить курсор в нужное место?


DivMan
 Share

Question

При клике на кнопку, в блок (с атрибутом contenteditable) помещается имя и оборачивается в элемент b и надо потом печатать после имени, если кликнуть потом в этот блок, то курсор не выходит за пределы элемента b и получается весь напечатанный текст будет тоже жирным, как вывести курсор за этот элемент?

 

Почему то selectionStart не работает.

<p style="
padding: 10px; 
background: white; 
width: 50%;" 
                   
contenteditable="true" class="write-comment"></p>

 

var formComment = document.querySelector('.write-comment');
var userNameHtml = document.createElement('b'); 
userNameHtml.innerHTML = userName + ',&nbsp;';
                
formComment.appendChild(userNameHtml);
formComment.focus();
formComment.selectionStart = formComment.innerHTML.length;

 

Link to comment
Share on other sites

1 answer to this question

Recommended Posts

  • 0
var formComment = document.querySelector('.write-comment');
formComment.innerHTML = '<b>' + userName + ',' + '</b>' + '&nbsp;';
formComment.appendChild(userNameHtml);

Можно так:

<p id='aaa' style="
padding: 10px; 
background: white; 
width: 50%;"                    
contenteditable="true" class="write-comment"></p> 
<button id="btn">Click me</button>
var userName = "Vasya Pupkin";

btn.onclick = function () {
  var formComment = document.querySelector(".write-comment");
  formComment.innerHTML = "<b>" + userName + "</b>" + ", ";
  formComment.focus();
  var sel = window.getSelection();
  var range = document.createRange();
  range.setStart(formComment, formComment.childNodes.length);
  range.collapse(true);
  sel.removeAllRanges();
  sel.addRange(range);
};

 

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue. See more about our Guidelines and Privacy Policy