2016-03-16 5 views
0

Привет Я хочу создать onfocus и onBlur события в Javascript. Я нашел решение, которое находится в JQuery, но не уверен, как преобразовать его в Javascript.Javascript OnFocus и события OnBlue

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

Приведенный выше код работает нормально. Любая помощь будет оценена, спасибо заранее.

+0

Почему бы не использовать jquery? –

+0

Я хочу знать, как это сделать в javascript. Все методы, которые у меня есть, находятся в Javascript. –

+0

http://ejohn.org/files/142/ проверить, почему jquery быстрее в производительности по ссылке –

ответ

1

Попробуйте так:

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
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 
1

Это код JavaScript для кода JQuery вы предоставили,

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); 
}