简体   繁体   English

如何使div元素可编辑(当我点击它时就像textarea一样)?

[英]How do I make a div element editable (like a textarea when I click it)?

This is my code: 这是我的代码:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
    <head> 
        <meta name="viewport" content="width=device-width, user-scalable=no"> 
    </head> 
<body> 
        <style type="text/css" media="screen"> 

        </style> 

        <!--<div id="map_canvas" style="width: 500px; height: 300px;background:blue;"></div>-->

        <div class=b style="width: 200px; height: 200px;background:pink;position:absolute;left:500px;top:100px;"></div>
        <script src="jquery-1.4.2.js" type="text/javascript"></script>
        <script src="jquery-ui-1.8rc3.custom.min.js" type="text/javascript"></script>
        <script type="text/javascript" charset="utf-8"> 

        </script> 
    </body> 
</html>

Thanks 谢谢

Let's work through it. 让我们来解决它。

You can't make a div editable. 你不能使div可编辑。 There's no such thing as an editable div, at least for now. 至少就目前而言,没有可编辑的div这样的东西。 So the problem is finding out what to use for editing instead. 所以问题是要找出用于编辑的内容。 A textarea works perfectly. textarea完美无缺。 So the idea is to somehow get a textarea where the div currently sits. 因此,想法是以某种方式得到div当前所在的textarea。

The question is how and from where do we get the textarea. 问题是我们如何以及从哪里获得textarea。 There are various ways, but one of them is to dynamically create a textarea on the fly: 有多种方法,但其中一种方法是动态创建textarea:

var editableText = $("<textarea />");

and replace it with the div: 并用div替换它:

$("#myDiv").replaceWith(editableText);

The textarea is in place now. textarea现在已经到位。 But it is empty and we have just replaced the div and lost everything. 但它是空的,我们刚刚更换了div而失去了一切。 So we need to preserve the text of the div somehow. 所以我们需要以某种方式保留div的文本。 One way is to copy the text/html inside the div before replacing it: 一种方法是在替换之前复制div中的text / html:

var divHtml = $("#myDiv").html(); // or text(), whatever suits.

Once we have the html from the div, we can populate the textarea and safely replace the div with the textarea. 一旦我们从div获得了html,我们就可以填充textarea并用textarea安全地替换div。 And set the focus inside the textarea as the user might want to start editing. 并在用户可能想要开始编辑时将焦点设置在textarea中。 Combining all the work upto this point, we get: 到目前为止,将所有工作结合起来,我们得到:

// save the html within the div
var divHtml = $("#myDiv").html();
// create a dynamic textarea
var editableText = $("<textarea />");
// fill the textarea with the div's text
editableText.val(divHtml);
// replace the div with the textarea
$("#myDiv").replaceWith(editableText);
// editableText.focus();

It's functional but nothing happens when a user clicks a div because we didn't setup any events. 它很实用,但是当用户点击div时没有任何反应,因为我们没有设置任何事件。 Let's wire up the events. 让我们联系这些事件。 When the user clicks any div $("div").click(..) , we create a click handler, and do all of the above. 当用户单击任何div $("div").click(..) ,我们创建一个单击处理程序,并执行上述所有操作。

$("div").click(function() {
    var divHtml = $(this).html(); // notice "this" instead of a specific #myDiv
    var editableText = $("<textarea />");
    editableText.val(divHtml);
    $(this).replaceWith(editableText);
    editableText.focus();
});

This is good, but we'd want a way to get our div back when a user clicks out or leaves the textarea. 这很好,但是当用户点击或离开textarea时,我们想要一种方法来恢复我们的div。 There is a blur event for form controls that is triggered when a user leaves the control. 当用户离开控件时,会触发表单控件的blur事件。 That can be used to detect when a user leaves the textarea, and replace back the div. 这可用于检测用户何时离开textarea,并替换div。 We do the exact reverse this time. 这次我们完全相反。 Preserve the value of textarea, create a dynamic div, set it's html, and replace out the textarea. 保留textarea的值,创建一个动态div,设置它的html,并替换textarea。

$(editableText).blur(function() {
    // Preserve the value of textarea
    var html = $(this).val();
    // create a dynamic div
    var viewableText = $("<div>");
    // set it's html 
    viewableText.html(html);
    // replace out the textarea
    $(this).replaceWith(viewableText);
});

Everything is great, except that this new div will no longer convert into a textarea on click. 一切都很棒,除了这个新的div不再能在点击时转换为textarea。 This is a newly created div, and we'll have to setup the click event again. 这是一个新创建的div,我们将不得不再次设置click事件。 We already have the entire code, but better than repeating it twice, it's better to make a function out of it. 我们已经拥有了整个代码,但比重复两次更好,最好用它来创建一个函数。

function divClicked() {
    var divHtml = $(this).html();
    var editableText = $("<textarea />");
    editableText.val(divHtml);
    $(this).replaceWith(editableText);
    editableText.focus();
    // setup the blur event for this new textarea
    editableText.blur(editableTextBlurred);
}

Since the whole operation is two-way reversible, we'll need to do the same for the textarea. 由于整个操作是双向可逆的,我们需要为textarea做同样的事情。 Let's convert that into a function too. 让我们把它转换成一个函数。

function editableTextBlurred() {
    var html = $(this).val();
    var viewableText = $("<div>");
    viewableText.html(html);
    $(this).replaceWith(viewableText);
    // setup the click event for this new div
    $(viewableText).click(divClicked);
}

Wiring up everything together, we have 2 functions, divClicked , editableTextBlurred and the line below triggers everything: 将所有内容连接在一起,我们有2个函数, divClickededitableTextBlurred ,下面的行触发了所有内容:

$("div").click(divClicked);

Checkout this code at http://jsfiddle.net/GeJkU/ . http://jsfiddle.net/GeJkU/上查看此代码。 This is not the best way of writing editable divs by any means, but just one way to start and approach the solution step by step. 这不是以任何方式编写可编辑div的最佳方法,而只是逐步启动和处理解决方案的一种方法。 Honestly I have learnt just as much as you in writing this long piece. 老实说,我在写这篇长篇文章时和你一样学到了很多东西。 Signing off, adios! 注销,adios!

To make a <div> (or any element for that matter) editable you can use the contenteditable HTML attribute. 要使<div> (或任何元素)可编辑,您可以使用contenteditable HTML属性。

For example: 例如:

 <div contenteditable="true">Anything inside this div will be editable!</div> 

More info here: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/contenteditable 更多信息: https//developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/contenteditable

使用contenteditable="true"属性进行划分。

Based on the answer of Anurag I wrote a small jquery plugin: 基于Anurag的答案我写了一个小的jquery插件:

https://github.com/zevero/jquery-html-editable https://github.com/zevero/jquery-html-editable

which allows you to make all 'div.myDiv' elements editable: 这允许您使所有'div.myDiv'元素可编辑:

$('body').html_editable('div.myDiv');

For those looking for an on() version, this is based on Anurag's answer. 对于那些寻找on()版本的人来说,这是基于Anurag的答案。

If, for some reason, you wanted to take the click event off the editable text input (eg for viewing editable and non editable versions of content), you could later apply $(document).off("click", ".editable_text"); 如果出于某种原因,您想要从可编辑文本输入中$(document).off("click", ".editable_text"); click事件(例如,查看可编辑和不可编辑的内容版本),您可以稍后应用$(document).off("click", ".editable_text"); .

 $(document).on("click", ".editable_text", function() { var original_text = $(this).text(); var new_input = $("<input class=\\"text_editor\\"/>"); new_input.val(original_text); $(this).replaceWith(new_input); new_input.focus(); }); $(document).on("blur", ".text_editor", function() { var new_input = $(this).val(); var updated_text = $("<span class=\\"editable_text\\">"); updated_text.text(new_input); $(this).replaceWith(updated_text); }); 
 .text_editor { border: none; background: #ddd; color: #000; font-size: 14px; font-family: arial; width: 200px; cursor: text; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p><span class="editable_text">Here is my original text.</span> </p> 

contenteditable has some grave defects. contenteditable有一些严重的缺陷。 The most damning in my view, is cross browser incompatability on Enter use. 在我看来,最诅咒的是在使用上跨浏览器不兼容。 See this article for a description. 有关说明,请参阅此文章 In Firefox clicking Enter for a carriage return creates a new paragraph, effectively double spacing every line that isn't long enough to wrap. 在Firefox中,单击Enter以进行回车创建一个新段落,有效地将每个行的双倍间距设置为不足以换行。 Very ugly. 十分难看。

can you try this one 你能试试这个吗?

 <!DOCTYPE html>
    <html>
    <body>

    <div id="myP">This is a paragraph. Click the button to make me editable.</div>

    <button onclick="myFunction()">Try it</button>

    <p id="demo"></p>

    <script>
    function myFunction() {
        document.getElementById("myP").contentEditable = true;
        document.getElementById("demo").innerHTML = "The p element above is now editable. Try to change its text.";
    }
    </script>

    </body>
    </html>

Here's a simple solution: 这是一个简单的解决方案:

$('div').click(function(e){
    this.contentEditable = 'true';
});

Working example at https://jsfiddle.net/pgdqhacj/2/ . https://jsfiddle.net/pgdqhacj/2/上的工作示例。 The only downside is that you have to double click to edit the text, not single click. 唯一的缺点是你必须双击编辑文本,而不是单击。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 jQuery:包含textarea值的div,当我单击div中的一个单词时,使其在textarea中单击 - Jquery: a div that contains the value of a textarea, when i click on a word in the div, make it click there in the textarea 单击按钮(包括内容)时,如何用textarea替换div? - How do I replace div with textarea when I click button (including content)? 如何从流星中的可编辑div中选择值而不是使用textarea.value? - How do I select value from editable div in meteor instead of using textarea.value? 如何使 textarea 内容可以设置样式或设置 div 行为,如 textarea 行为? - How can I make textarea content possible to styling or set div behaviour like textarea behaviour? 我怎么做 <div> 进入 <textarea> 单击“输入键盘按钮”时是否也要复制换行符? - How do I make <div> into <textarea> copy to copy the line break too when hitting “enter keyboard button”? 当我单击同一div或在div之外时,如何隐藏和切换popover元素? - How do i hide and toggle popover element when i click on the same div or outside of the div? 当我单击对应的复选框时,如何使不可编辑的文本框变为可编辑的 - How to make non editable text box to editable when i click on check box corresponding to it 当我在div元素中单击child时,如何使孩子被调用 - how can I make just child invoked when I click on child in the div element 如何使UI元素可编辑? - How can I make a UI element editable? 单击div时如何将元素恢复为默认状态? (jQuery的) - How do I revert back an element to default state when I click a div? (jQuery)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM