当前位置:Gxlcms > JavaScript > 文本框(input)获取焦点(onfocus)时样式改变的示例代码_javascript技巧

文本框(input)获取焦点(onfocus)时样式改变的示例代码_javascript技巧

时间:2021-07-01 10:21:17 帮助过:24人阅读

摘要:许多重视用户体验的设计师都希望给文本框(input)加上获取焦点或者鼠标悬停时的样式切换效果。其实很简单,我们只需要获取页面上的文本框,加上onfocus事件或者其他对应的事件即可。本文介绍了如何在获取焦点时切换样式,明白原理后,实现其他效果就很简单了。

许多重视用户体验的设计师都希望给文本框(input)加上获取焦点或者鼠标悬停时的样式切换效果。其实很简单,我们只需要获取页面上的文本框,加上onfocus事件或者其他对应的事件即可。本文介绍了如何在获取焦点时切换样式,明白原理后,实现其他效果就很简单了。

代码如下:

function focusInput(focusClass, normalClass) {
var elements = document.getElementsByTagName("input");
for (var i=0; i < elements.length; i++) {
if (elements[i].type != "button" && elements[i].type != "submit" && elements[i].type != "reset") {
//if(elements[i].type=="text"){
elements[i].onfocus = function() { this.className = focusClass; };
elements[i].onblur = function() { this.className = normalClass||''; };
}
}
}

window.onload = function() {
focusInput('focusInput', 'normalInput');
}


代码如下:


人气教程排行