简体   繁体   English

如何改变<div>进入<input>通过点击

[英]How to change <div> into <input> by onclick

I have <p> a certain text </p> I want by onClick to changes this into a <input value="certain text"> , so it can be edited.我有<p>某个文本</p>我希望通过onClick将其更改为<input value="certain text"> ,以便可以对其进行编辑。

All the solutions I found were clicking on a button.我找到的所有解决方案都是点击一个按钮。 I want the text hides and the input-field appears instead.我希望文本隐藏而输入字段出现。

 function makeInput(e) { e.innerHTML = '<input value="'+e.innerText+'">'; }
 <p onclick="makeInput(this)">a certain value</p>

A possible alternative is to just make the content of the p tag editable and use javascript to submit the information without using a input tag.一种可能的替代方法是仅使 p 标签的内容可编辑,并使用 javascript 提交信息而不使用输入标签。

 <p contenteditable="true">This is an editable paragraph.</p>

Click to Edit, click away when done editing.单击以编辑,完成编辑后单击离开。

HTML: HTML:

<div class="editable">
   Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
   Nullam dapibus porttitor sem, et tristique neque vehicula eu. 
   Nulla porta ex semper sapien luctus bibendum. Donec et congue nisi
</div>

CSS: CSS:

textarea {
  width: 100%;
  max-width: 400px;
  padding: 10px 20px;
  min-height: 120px
}

JS: JS:

var eventHandler = function(e){e.preventDefault(); editDiv(this);};
document.querySelector('.editable').addEventListener("click", eventHandler);

function editDiv(div){
  var text = div.innerText,
      textarea = document.createElement("TEXTAREA");
  textarea.value = text;

  div.innerHTML = "";
  div.append(textarea);
    textarea.focus();
  textarea.addEventListener("focusout", function(e){
    finishEditDiv(div);
  });

  div.removeEventListener("click", eventHandler);

}

function finishEditDiv(div){
  //handle your data saving here
  var text = div.querySelector('textarea').value;
  div.innerHTML = text;
  document.querySelector('.editable').addEventListener("click", eventHandler);
}

Assign the onClick to the p tag.onClick分配给 p 标签。

Create an hidden input.创建一个隐藏的输入。

On click hide the current p, and get the input associated to that p, then display it.单击隐藏当前 p,并获取与该 p 关联的输入,然后显示它。

 function onClick(e) { e.currentTarget.style.display = 'none'; document.querySelector('#p-input').style.display = 'block'; }
 <section> <p onClick="onClick(event)">Clickable text</p> <input id="p-input" style="display:none;" type="text" /> </section>

You may use input element only.您只能使用 input 元素。 Use a disabled input with a styling of your choice ( grayish background for example ).使用具有您选择的样式的禁用输入(例如,灰色背景)。 Use onClick event to set the input to active and change its style ( no background ).使用 onClick 事件将输入设置为活动并更改其样式(无背景)。

Worked pretty good for me.对我来说效果很好。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM