我有一个文本字段,可以使用click进行编辑,我在jQuery中进行编辑。
现在我想知道当我点击EDIT button
编辑代码
$('.edit').click(function () {
$(this).siblings('.edit-section').attr('contenteditable', 'true');
$(this).siblings('.edit-section').attr('style', 'border:2px solid;');
$(this).attr('style', 'display:none;');
$(this).siblings('.done').attr('style', 'display:li;');
});
我无法为.edit-section
添加单独的点击功能答案 0 :(得分:3)
尝试,
$('.edit,.done').click(function () {
var section = $(this).siblings('.edit-section');
var isEdit = $(this).is('.edit');
section.prop('contenteditable',isEdit).css('border',isEdit?"2px solid":"none");
$('.edit').toggle(!isEdit);
$('.done').toggle(isEdit);
if(isEdit){section.focus(); document.execCommand('selectAll',false,null); }
});
答案 1 :(得分:3)
<强> Demo 强>
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);
}
};
$(".edit").click(function () {
$(".edit-section").selectText();
});
来自:Selecting text in an element (akin to highlighting with your mouse)
答案 2 :(得分:2)
可能重复 - Programmatically select text in a contenteditable HTML element?
从答案中复制以下功能。
function selectElementContents(el) {
var range = document.createRange();
range.selectNodeContents(el);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
var el = document.getElementById("foo");
selectElementContents(el);
更新了JS-Fiddle - http://jsfiddle.net/vishwanatharondekar/zSwBL/5/
答案 3 :(得分:1)
尝试
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);
}
};
$("button").click(function() {
$("#editable").selectText();
});