标签: 双击文本修改

  • 双击实现文本元素修改

    此效果多应用于后台栏目名称修改上,双击以创建input元素,onblur事件实现异步调用无刷新提交。

    JS部分:

    <code><script type=”text/javascript”>
    function showInput(element)
    {
    var defaultValue = element.innerHTML;   //取得默认内容
    var inputEle= document.createElement(‘input’);   //创建input元素
    inputEle.type = ‘text’;   //添加类型
    inputEle.value=defaultValue;
    inputEle.className=”tip”;
    element.innerHTML = ”;
    element.appendChild(inputEle);   //添加子元素
    inputEle.focus();   //获得焦点
    inputEle.onfocus = function()
    {
    element.ondblclick=”;//取消元素的双击事件
    }
    inputEle.onblur = function()
    {
    element.innerHTML = this.value ? this.value : defaultValue;   //触发时判断值是否为空
    var any= $(this).attr(‘value’);
    $.ajax({
    type: “POST”,
    url: “insert.php”,
    data: “name=”+ any,
    success: function(){
    $(“#show”).prepend(“<li>提交成功:”+any+”</li>”);
    $(“#show li:first”).fadeIn(“slow”);
    }
    });
    element.ondblclick = function()//还原
    {
    showInput(this);
    }
    }
    }
    </script></code>

    样式:

    <style type=”text/css” media=”all”>
    #show{
    margin-top:100px;
    width:300px;
    height:200px;
    border:1px solid #F5F5F5;
    overflow:hidden;
    }
    #show li{
    background:#FDF5E6;
    list-style:none;
    }
    .tip{
    border:2px solid #FDF5E6;
    }
    </style>

    HTML部分:

    <span>双击下面文字:</span>  <br /><br />
    <span ondblclick=”showInput(this)” >天道酬勤</span> <br />
    <div id=”show”></div>

    注意,该效果的实现用到了jQuery,请在HTML头部包含之。

    点击预览效果.