我有一些简单的代码用于向列表中添加新的项目符号。新的要点包含用户随后编辑的“您的新子弹”的通用文本。有没有办法,一旦添加了新的项目符号点,就会选择通用文本进行覆盖。
我的代码看起来像这样......
$(document).on("click", "#addNewBullet", function(){
$('<li class="bullet editable" contentEditable="true">Your new bullet</li>').insertBefore('#addNewBullet')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="bulletPoints" id="bullets">
<li class="bullet" contenteditable="true">Bullet1</li>
<li class="bullet" contenteditable="true">Bullet2</li>
<li class="bullet" contenteditable="true">Bullet3</li>
<div id="addNewBullet">+ Add</div>
</ul>
由于
答案 0 :(得分:1)
使用focus
,我添加了功能selectText
来选择所有文字,以便于编辑文字。
jQuery.fn.selectText = function(){
var doc = document;
var element = this[0];
console.log(this, element);
if (doc.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(element);
range.select();
} else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
};
$(document).on("click", "#addNewBullet", function() {
$('<li class="bullet editable" contentEditable="true">Your new bullet</li>').insertBefore('#addNewBullet').focus().selectText();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="bulletPoints" id="bullets">
<li class="bullet" contenteditable="true">Bullet1</li>
<li class="bullet" contenteditable="true">Bullet2</li>
<li class="bullet" contenteditable="true">Bullet3</li>
<div id="addNewBullet">+ Add</div>
</ul>
答案 1 :(得分:0)
您可以使用.focus()
然后选择所有文字:
$(document).on("click", "#addNewBullet", function() {
$('<li class="bullet editable" contentEditable="true">Your new bullet</li>').insertBefore('#addNewBullet').focus();
document.execCommand('selectAll', false, null);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="bulletPoints" id="bullets">
<li class="bullet" contenteditable="true">Bullet1</li>
<li class="bullet" contenteditable="true">Bullet2</li>
<li class="bullet" contenteditable="true">Bullet3</li>
<div id="addNewBullet">+ Add</div>
</ul>