div 요소를 편집 가능하게 만들려면 어떻게해야합니까 (클릭 할 때 텍스트 영역처럼)?
이것은 내 코드입니다.
<!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>
감사
그것을 통해 일합시다.
div를 편집 가능하게 만들 수 없습니다. 적어도 지금은 편집 가능한 div와 같은 것이 없습니다. 따라서 문제는 대신 편집에 사용할 것을 찾는 것입니다. 텍스트 영역은 완벽하게 작동합니다. 그래서 아이디어는 어떻게 든 div가 현재 위치하는 텍스트 영역을 얻는 것입니다.
문제는 텍스트 영역을 어떻게 그리고 어디에서 얻 느냐입니다. 다양한 방법이 있지만 그 중 하나는 즉석에서 동적으로 텍스트 영역을 만드는 것입니다.
var editableText = $("<textarea />");
div로 바꿉니다.
$("#myDiv").replaceWith(editableText);
이제 텍스트 영역이 제자리에 있습니다. 그러나 그것은 비어 있고 우리는 방금 div를 교체하고 모든 것을 잃었습니다. 그래서 우리는 어떻게 든 div의 텍스트를 보존해야합니다. 한 가지 방법은 교체하기 전에 div 내부의 text / html을 복사하는 것입니다.
var divHtml = $("#myDiv").html(); // or text(), whatever suits.
div에서 html을 가져 오면 텍스트 영역을 채우고 div를 텍스트 영역으로 안전하게 대체 할 수 있습니다. 그리고 사용자가 편집을 시작하고 싶을 수 있으므로 텍스트 영역 내부에 포커스를 설정합니다. 지금까지의 모든 작업을 결합하면 다음과 같은 결과를 얻을 수 있습니다.
// 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();
기능적이지만 이벤트를 설정하지 않았기 때문에 사용자가 div를 클릭해도 아무 일도 일어나지 않습니다. 이벤트를 연결합시다. 사용자가 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();
});
이것은 좋지만 사용자가 텍스트 영역을 클릭하거나 떠날 때 div를 다시 가져올 수있는 방법을 원합니다. blur사용자가 컨트롤을 떠날 때 트리거되는 양식 컨트롤에 대한 이벤트 가 있습니다 . 사용자가 텍스트 영역을 벗어날 때이를 감지하고 div를 다시 대체하는 데 사용할 수 있습니다. 이번에는 정반대로합니다. 텍스트 영역의 값을 유지하고, 동적 div를 만들고, html로 설정하고, 텍스트 영역을 대체합니다.
$(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);
});
이 새로운 div가 더 이상 클릭시 텍스트 영역으로 변환되지 않는다는 점을 제외하면 모든 것이 훌륭합니다. 이것은 새로 생성 된 div이며 click이벤트를 다시 설정해야 합니다. 우리는 이미 전체 코드를 가지고 있지만 두 번 반복하는 것보다 함수를 만드는 것이 좋습니다.
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);
}
전체 작업은 양방향으로 되돌릴 수 있으므로 텍스트 영역에 대해서도 동일하게 수행해야합니다. 이것도 함수로 변환 해 봅시다.
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);
}
모든 것을 함께 묶기, 우리는이 개 기능을 가지고 divClicked, editableTextBlurred트리거 모든 것을 아래의 라인을 :
$("div").click(divClicked);
http://jsfiddle.net/GeJkU/ 에서이 코드를 확인하세요 . 이것은 편집 가능한 div를 작성하는 가장 좋은 방법은 아니지만 단계별로 솔루션을 시작하고 접근하는 한 가지 방법 일뿐입니다. 솔직히이 긴 글을 쓰면서 당신만큼 배웠습니다. 사인 오프, adios!
a를 위해 <div>(그 문제에 대한 또는 요소) 당신이 사용할 수있는 편집 가능한 contenteditableHTML 속성을.
예를 들면 :
<div contenteditable="true">Anything inside this div will be editable!</div>
자세한 정보 : https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/contenteditable
Use contenteditable="true" attributes for the division.
Based on the answer of Anurag I wrote a small jquery plugin:
https://github.com/zevero/jquery-html-editable
which allows you to make all 'div.myDiv' elements editable:
$('body').html_editable('div.myDiv');
For those looking for an on() version, this is based on Anurag's answer.
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).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. 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. 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/. The only downside is that you have to double click to edit the text, not single click.
ReferenceURL : https://stackoverflow.com/questions/2441565/how-do-i-make-a-div-element-editable-like-a-textarea-when-i-click-it
'programing' 카테고리의 다른 글
| 원격 git 저장소에서 최신 커밋의 SHA를 얻는 방법은 무엇입니까? (0) | 2021.01.16 |
|---|---|
| 자체 버그 추적 시스템을 구축하지 않는 이유 (0) | 2021.01.16 |
| instanceof-호환되지 않는 조건부 피연산자 유형 (0) | 2021.01.16 |
| Android : MediaPlayer setVolume 함수 (0) | 2021.01.16 |
| 자바 InputStream 모의 (0) | 2021.01.16 |