如何替换用图像替换单选按钮? [英] How to replace replace radio buttons with images?
问题描述
我想,而不是标准的单选按钮,为每个单选按钮使用不同的图像。对于选择的状态,我想要一个边框出现在图像周围。
我已经尝试为单选按钮制作图像标签,然后隐藏按钮,但是这似乎由于某种原因打破了功能。
我也遇到了这篇文章: http://ryanfait.com/resources/custom-checkboxes-and-radio-buttons/ ,我可能会以某种方式扭曲我的目的。
有更容易/更好的方法吗?
jQuery
$ b
$('input:radio')hide()每个函数(){
$(this).attr -radio-fx',this.name);
var label = $(label [for =+''+ this.id +''+] $ b $('< a'+(label!=''?'title ='+ label +'':'')+'data-radio-fx ='+ this.name +'class = radio-fxhref =#>'+
'< span class =radio+(this.checked? 'radio-checked':'')+'>< / span>< / a>')insertAfter(this);
});
$('a.radio- fx')。on('click',function(e){
e.preventDefault();
var unique = $(this).attr('data-radio-fx');
$(a [data-radio-fx ='+ unique +'] span)。attr('class','radio');
$(:radio [data-radio-fx ='+ unique +'])attr('checked',false);
$(this).find('span')。attr('class','radio-checked');
$(this).prev('input:radio')。attr('checked',true);
})on('keydown',function(e){
if (e.keyCode?e.keyCode:e.which)== 32){
$(this).trigger('click');
}
});
$ c $ p>
- 演示源中的完整代码;
I would like to, instead of the standard radio button, use distinct images for each radio button. For the selected state I would like for a border to appear around the image.
I have tried making the images labels for the radio button and then hiding the button, but that seems to break the functionality for some reason.
I also have come across this article: http://ryanfait.com/resources/custom-checkboxes-and-radio-buttons/ which I could potentially somehow twist to my purposes.
Is there an easier/better way?
解决方案
jQuery
$('input:radio').hide().each(function() {
$(this).attr('data-radio-fx', this.name);
var label = $("label[for=" + '"' + this.id + '"' + "]").text();
$('<a ' + (label != '' ? 'title=" ' + label + ' "' : '' ) + ' data-radio-fx="'+this.name+'" class="radio-fx" href="#">'+
'<span class="radio' + (this.checked ? ' radio-checked' : '') + '"></span></a>').insertAfter(this);
});
$('a.radio-fx').on('click', function(e) {
e.preventDefault();
var unique = $(this).attr('data-radio-fx');
$("a[data-radio-fx='"+unique+"'] span").attr('class','radio');
$(":radio[data-radio-fx='"+unique+"']").attr('checked',false);
$(this).find('span').attr('class','radio-checked');
$(this).prev('input:radio').attr('checked',true);
}).on('keydown', function(e) {
if ((e.keyCode ? e.keyCode : e.which) == 32) {
$(this).trigger('click');
}
});
- full code in demo source;
这篇关于如何替换用图像替换单选按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!