老项目要升级改版,对于分散在各页面的样式不好处理,怕有遗漏,尤其是优化input表单,修改其默认样式,接下来,我将给大家分享一下,我在项目中的总结。
本文为Echoyya、所创,转载请带上原文链接,感谢 https://www.cnblogs.com/echoyya/p/14126709.html
效果
上代码:
2.简单搞一搞 HTML
<input type="radio" name="yesOrNo" id="yes" checked />
<label for="yes">是</label>
<input type="radio" name="yesOrNo" id="no" />
<label for="no">否</label>
3.开整 ~~~~
首先分析一下实现思路:
定义一个JQuery的扩展方法,页面加载完毕,input radio循环调用
创建一个新的Div,并设置类名,用于定义css
使用输入的ID得到相关的标签,将input radio及对应的id的label,放进上述Div中
绑定自定义事件,触发它,绑定点击,焦点等事件
<script src="./jquery-1.11.1.min.js"></script>
<script>
$.fn.customInput = function () {
return $(this).each(function () {
if ($(this).is('[type=radio]')) {
var input = $(this);
var label = $('label[for=' + input.attr('id') + ']');
label.add(input).wrapAll('<div class="custom-' + input.attr('type') + '"></div>');
label.hover = function () {
$(this).addClass('hover');
};
input.bind('updateState', function () {
input.is(':checked') ? label.addClass('checked') : label.removeClass('checked');
})
.click(function () {
$('input[name=' + $(this).attr('name') + ']').trigger('updateState');
})
.focus(function () {
// 自定义处理逻辑
label.addClass('focus');
if (input.is(':checked')) $(this).addClass('checkedFocus');
})
.blur(function () {
// 自定义处理逻辑
label.removeClass('focus checkedFocus');
});
}
});
};
$('input:radio').each(function () {
var $this = $(this);
$this.customInput(); //初始化单选框
});
</script>