Javascript OnFocus和OnBlue事件

时间:2016-03-16 06:15:37

标签: javascript jquery javascript-events onblur onfocus

您好我想在Javascript中创建onfocus和onBlur事件。我找到了一个在Jquery中的解决方案,但不知道如何将其转换为Javascript。

<textarea id='postitTextArea'  ></textarea>
$('input,textarea').focus(function()
{
  $(this).data('placeholder', $(this).attr('placeholder'))
        .attr('placeholder', '');
}).blur(function()
{
  $(this).attr('placeholder', $(this).data('placeholder'));
});

上面的代码工作正常。任何帮助将不胜感激,提前谢谢。

3 个答案:

答案 0 :(得分:2)

试试这样:

var obj = document.getElementById('postitTextArea');

obj.removeAttribute('onfocus');
obj.removeAttribute('onblur');

obj.addEventListener('focus', function() {
  // your js code for focus event
});
obj.addEventListener('blur', function() {
   // your js code for blur event
});

答案 1 :(得分:1)

var inputs, index;

inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
    inputs[index].onfocus = function(){
     // Your script
    };
    inputs[index].onblur = function(){
     // Your script
    };
}

//similarly for textarea

答案 2 :(得分:1)

这是您提供的jQuery代码的JavaScript代码,

HTML:

<textarea id='postitTextArea' placeholder="placeholder text" onfocus="focusAction()" onblur="blurAction()"></textarea>

JS:

function focusAction(){
    var target = document.getElementById('postitTextArea');
    var setAttrVal = target.setAttribute('placeholder',' ');
    console.log('placeholder: ' + setAttrVal);
}
function blurAction(){
    var target = document.getElementById('postitTextArea');
    var setAttrVal = target.setAttribute('placeholder','placeholder text');
    console.log('placeholder: ' + setAttrVal);
}