单击时使用javascript将某些文本更改为输入字段 [英] using javascript to change some text into an input field when clicked on

查看:103
本文介绍了单击时使用javascript将某些文本更改为输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个具有一些可编辑字段的页面,但我只希望它们在用户点击它们时显示为输入框(其余时间显示为纯文本)。在Javascript中有一种简单的方法吗?

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?

推荐答案

简介



相当简单,是的。我可以想到两种基本方法:

Introduction

Fairly simple, yes. I can think of two basic approaches:


  • 使用 contenteditable 属性

  • 使用输入即时添加

  • Using the contenteditable attribute
  • Using an input you add on-the-fly

以下两个方便的参考:

  • DOM2 Core
  • DOM2 HTML
  • DOM3 Core
  • HTML5 spec - "user interaction" section

contentEditable 属性( W3C MDC MSDN )可以是真实的表示可以直接编辑元素。这样做的好处是根本不需要任何JavaScript(实例):

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):

<p id="container">The <span contenteditable="true">colored items</span> in this paragraph
are <span contenteditable="true">editable</span>.</p>

为免你认为这是一些l33t新东西,IE已经支持IE 5.5和其他主流浏览器差不多长了。 (事实上​​,这是IE5.5 / IE6时间框架中的众多微软创新之一;它们还为我们提供了 innerHTML 和Ajax。)

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.)

如果你想获取(编辑过的)内容,你只需从你可编辑的元素中获取 innerHTML 。下面是一些JavaScript的例子,当 contenteditable 跨越 blur 时,它会被标记出来(实时副本):

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):

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, "&amp").replace(/</g, "&lt;");
            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>

你需要获得你用于显示的元素的引用(可能是一个 span ),然后挂钩它的点击 event(或在所需元素的父元素上挂钩单击事件)。在中单击事件,隐藏 span 并插入输入[type = text] 旁边。

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.

这是使用输入的非常简单的示例

Here's a very simple example of using an 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 == "" ? "&nbsp;" : 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>

我在 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.

在这种情况下,我使用 blur 再次进行编辑,但您可能希望有一个OK按钮和/或其他触发器(如Enter键)。

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).

偏离主题:您可能已经注意到上面的JavaScript代码中我必须处理几个MS差异(例如,IE与其他浏览器不同的东西),我使用旧的DOM0风格的事件处理程序,你只需要为一个属性分配一个函数,这是不理想的,但它避免了我必须处理另一个的区别,其中某些版本的IE没有DOM2 addEventListener ,所以你必须回退到 attachEvent

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 another difference where some versions of IE don't have the DOM2 addEventListener and so you have to fall back to attachEvent.

我的观点是:您可以通过使用体面的JavaScrip来平滑浏览器差异并获得大量实用功能t库如 jQuery Prototype YUI 关闭,或其中任何一个。你没有说你正在使用任何库,所以我没有在上面,但有令人信服的理由使用它们,所以你不必担心所有的小浏览器的琐事,并可以继续解决你的问题实际业务需求。

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.

这篇关于单击时使用javascript将某些文本更改为输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆