使用jQuery编辑和选择文本

时间:2014-07-30 10:34:09

标签: javascript jquery html css

我有一个文本字段,可以使用click进行编辑,我在jQuery中进行编辑。

现在我想知道当我点击EDIT button

时如何选中框中的所有文字

Fiddle Link

编辑代码

 $('.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

添加单独的点击功能

4 个答案:

答案 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); }
 });

DEMO


Source

答案 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();
});

JSFiddle

参考:How to select all text in contenteditable div?