占位符删除焦点(没有 jq)

时间:2020-12-23 07:47:39

标签: javascript

我如何删除焦点上的占位符并在模糊时再次重置它? (仅限 JavaScript)

我试过了:

const input = document.getElementById('input');

// This code is for clear placeholder value
if(input.placeholder){
    input.addEventListener('focus' , (e) => {
        input.placeholder = '';
    });
}else {
    input.addEventListener( 'blur' , () => {
        input.placeholder = 'hi'
    });
};

它的工作,但我不知道如何重置以前的值。

3 个答案:

答案 0 :(得分:1)

const input = document.getElementById('input');

// a variable to hold the placeholder value
let placeholerValue = ""

input.addEventListener('focus', (e) => {
  // saving the placeholder value in a variable
  placeholderValue = input.placeholder
  console.log("Saving", placeholderValue)

  // clearing the placeholder
  input.placeholder = '';
  console.log("Clearing!")
});

input.addEventListener('blur', () => {
  // restoring the placeholder from the variable
  input.placeholder = placeholderValue
  console.log("Restoring", placeholderValue)
});
<input id="input" type="text" placeholder="whatever">

答案 1 :(得分:0)

简单地说:

const input = document.getElementById('input');


input.onfocus = () =>
  {
  if (!input.placeholerValue) input.placeholerValue = input.placeholder
  input.placeholder = ''
  }
input.onblur = () =>
  {
  input.placeholder = input.placeholerValue 
  }

答案 2 :(得分:0)

Try if want single-line solution for it

<input id="input" type="text" onfocus="this.placeholder=''" onblur="this.placeholder= this.getAttribute('data-placeholder')" data-placeholder="whatever" placeholder="whatever" value="">

相关问题