Javascript 单击时使用javascript将一些文本更改为输入字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6814062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
using javascript to change some text into an input field when clicked on
提问by Philbert McPleb
I'm trying to make a page that has some editabable fields, but I only want them to display as input boxes once the user clicks on them (the rest of the time showing as plain text). Is there a simple way to do this in Javascript?
我正在尝试制作一个包含一些可编辑字段的页面,但我只希望它们在用户单击它们时显示为输入框(其余时间显示为纯文本)。有没有一种简单的方法可以在 Javascript 中做到这一点?
回答by T.J. Crowder
Introduction
介绍
Fairly simple, yes. I can think of two basic approaches:
相当简单,是的。我可以想到两种基本方法:
- Using the
contenteditable
attribute - Using an
input
you add on-the-fly
- 使用
contenteditable
属性 - 使用
input
您即时添加的
Handy references for both of the below:
以下两者的方便参考:
Using the contenteditable
attribute
使用contenteditable
属性
The contentEditable
attribute (W3C, MDC, MSDN) can be "true" indicating that the element can be edited directly. This has the advantage of not requiring any JavaScript at all (live example):
的contentEditable
属性(W3C,MDC,MSDN)可以是“真”指示该元件可以直接编辑。这具有根本不需要任何 JavaScript 的优点(现场示例):
<p id="container">The <span contenteditable="true">colored items</span> in this paragraph
are <span contenteditable="true">editable</span>.</p>
Lest you think this is some l33t new thing, IE has supported it since IE 5.5 and other major browsers for very nearly that long. (In fact, this was one of many Microsoft innovations from the IE5.5 / IE6 timeframe; they also gave us innerHTML
and Ajax.)
免得您认为这是一些新事物,自 IE 5.5 和其他主要浏览器以来,IE 一直支持它。(事实上,这是微软在 IE5.5/IE6 时间框架内的众多创新之一;他们还给了我们innerHTML
和 Ajax。)
If you want to grab the (edited) content, you just grab innerHTML
from the elements you've made editable. Here's an example of some JavaScript that will flag up when contenteditable
spans blur
(live copy):
如果您想获取(已编辑的)内容,只需innerHTML
从您已设置为可编辑的元素中获取即可。下面是一些 JavaScript 的示例,它会在contenteditable
跨度blur
(实时复制)时进行标记:
var spans = document.getElementsByTagName("span"),
index,
span;
for (index = 0; index < spans.length; ++index) {
span = spans[index];
if (span.contentEditable) {
span.onblur = function() {
var text = this.innerHTML;
text = text.replace(/&/g, "&").replace(/</g, "<");
console.log("Content committed, span " +
(this.id || "anonymous") +
": '" +
text + "'");
};
}
}
#container span {
background-color: #ff6;
}
<p id="container">The <span id="span1" contenteditable="true">colored items</span> in this paragraph
are <span contenteditable="true">editable</span>.</p>
Using an input
you add on-the-fly
使用input
您即时添加的
You need to get a reference to the element that you're using for display (a span
, perhaps) and then hook its click
event (or hook the click
event on a parent of the desired element(s)). In the click
event, hide the span
and insert a input[type=text]
alongside it.
您需要获取对用于显示的元素的引用(span
可能是 a ),然后挂钩其click
事件(或挂钩click
所需元素的父级上的事件)。在这种情况click
下,隐藏span
并在其input[type=text]
旁边插入一个。
Here's a very simpleexample of using an input
:
这是使用的一个非常简单的示例input
:
window.onload = function() {
document.getElementById('container').onclick = function(event) {
var span, input, text;
// Get the event (handle MS difference)
event = event || window.event;
// Get the root element of the event (handle MS difference)
span = event.target || event.srcElement;
// If it's a span...
if (span && span.tagName.toUpperCase() === "SPAN") {
// Hide it
span.style.display = "none";
// Get its text
text = span.innerHTML;
// Create an input
input = document.createElement("input");
input.type = "text";
input.value = text;
input.size = Math.max(text.length / 4 * 3, 4);
span.parentNode.insertBefore(input, span);
// Focus it, hook blur to undo
input.focus();
input.onblur = function() {
// Remove the input
span.parentNode.removeChild(input);
// Update the span
span.innerHTML = input.value == "" ? " " : input.value;
// Show the span again
span.style.display = "";
};
}
};
};
#container span {
background-color: #ff6;
}
<p id="container">The <span>colored items</span> in this paragraph
are <span>editable</span>.</p>
There I'm hooking the click
on the parent p
element, not the individual spans, because I wanted to have more than one and it's easier to do that. (It's called "event delegation.") You can find the various functions used above in the references I gave at the beginning of the answer.
我click
在父p
元素上挂钩,而不是单个跨度,因为我想拥有多个跨度,而且这样做更容易。(它被称为“事件委托”。)您可以在我在答案开头给出的参考资料中找到上面使用的各种函数。
In this case I used blur
to take the edit down again, but you may wish to have an OK button and/or other triggers (like the Enter key).
在这种情况下,我曾经blur
再次取消编辑,但您可能希望有一个 OK 按钮和/或其他触发器(如 Enter 键)。
Off-topic: You may have noticed in the JavaScript code above that I had to handle a couple of "MS differences" (e.g., things that IE does differently from other browsers), and I've used the old "DOM0" style of event handler where you just assign a function to a property, which isn't ideal, but it avoids my having to handle yet anotherdifference where some versions of IE don't have the DOM2 addEventListener
and so you have to fall back to attachEvent
.
题外话:您可能已经注意到,在上面的 JavaScript 代码中,我必须处理一些“MS 差异”(例如,IE 与其他浏览器的不同之处),并且我使用了旧的“DOM0”样式事件处理程序,您只是将一个函数分配给一个属性,这并不理想,但它避免了我必须处理另一个差异,即某些版本的 IE 没有 DOM2 addEventListener
,因此您必须回退到attachEvent
.
My point here is: You can smooth over browser differences and get a lot of utility functions as well by using a decent JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others. You didn't say you were using any libraries, so I didn't in the above, but there are compelling reasons to use them so you don't have to worry about all the little browser niggles and can just get on with addressing your actual business need.
我的观点是:通过使用像jQuery、Prototype、YUI、Closure或其他几个像样的 JavaScript 库,您可以平滑浏览器差异并获得许多实用功能。你没有说你在使用任何库,所以我没有在上面,但是使用它们有令人信服的理由,所以你不必担心所有浏览器的小问题,可以继续解决你的问题实际业务需要。
回答by pimvdb
A trivial example using plain JavaScript would be along the lines of: http://jsfiddle.net/vzxW4/.
使用纯 JavaScript 的一个简单示例如下:http: //jsfiddle.net/vzxW4/。
document.getElementById('test').onclick = function() {
document.body.removeChild(this);
var input = document.createElement('input');
input.id = 'test';
input.value = this.innerHTML;
document.body.appendChild(input);
input.select();
}
Using a library would save you time and headaches, though. For example, using jQuery: http://jsfiddle.net/vzxW4/1/.
但是,使用库可以节省您的时间和麻烦。例如,使用 jQuery:http: //jsfiddle.net/vzxW4/1/。
$("#test").click(function() {
var input = $("<input>", { val: $(this).text(),
type: "text" });
$(this).replaceWith(input);
input.select();
});
回答by Jatin Dhoot
Can we do it simple guys?
我们可以做简单的人吗?
Just keep textbox with readonly property true and some CSS which makes text box looks like span with border.
只需保持带有 readonly 属性的文本框为 true 和一些使文本框看起来像带边框的跨度的 CSS。
Then as soon as user clicks on text box remove readonly attribute.
然后只要用户点击文本框删除只读属性。
On blur restore the CSS and readonly attributes.
在模糊上恢复 CSS 和只读属性。