如何用图像替换单选按钮? [英] How to replace radio buttons with images?
问题描述
我想代替标准单选按钮,对每个单选按钮使用不同的图像.对于选定状态,我希望在图像周围出现边框.
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.
我也遇到过这篇文章: http://ryanfait. com/resources/custom-checkboxes-radio-buttons/,我可能会以某种方式扭曲我的意图.
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?
推荐答案
- DEMO: http://so.lucafilosofi.com/is-there-an-easy-way-to-replace-radio-button-with-images-and-a-colored-border-fo/
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屋!