通过jQuery或其他方式使用图标实现图形选择列表

时间:2010-08-23 15:35:53

标签: javascript jquery html jquery-plugins selectlist

我正在实现一个HTML表单。对于其中一个字段(天气),用户必须选择一组选项中的一个(晴天,阴天,下雨等)

所以基本上我正在寻找一个很好的替代<select><radio>,它提供了一系列图像(我将提供)供用户选择。我会为每个图像创建代表未选项的暗淡/灰色版本。

我发现大量的jQuery评级控件提供了这个,但没有什么能完全符合我的要求(可能是因为我真的不知道它叫什么,所以不能谷歌它。)

哦,如果用户没有启用JavaScript,它应该很好地降级,以提供标准的<select><radio>选项。

1 个答案:

答案 0 :(得分:3)

你可以轻松地自己动手。从标记开始如下:

<fieldset>
    <input type="radio" name="weather" value="sunny" />
    <input type="radio" name="weather" value="cloudy" />
    <input type="radio" name="weather" value="rainy" />
    <input type="radio" name="weather" value="class-3-kill-storm" />
</fieldset>

如果没有启用javascript,用户将获得上述内容(您可能希望添加一些标签元素,以便人们知道他们点击了什么;)。接下来,遍历所有这些元素并创建图标所需的<a>元素:

$('input[name=weather]').each(function() {
    var radio = $(this);
    radio.css({display: 'none'});

    var icon = $('<a class="icon ' + this.value + '"></a>');
    icon.click(function(e) {
        // stop default link click behaviour
        e.preventDefault();

        // unmark any previously selected image and mark clicked selected
        icon.siblings('.icon').removeClass('selected');
        icon.addClass('selected');

        // set associated radio button's value
        radio.attr('checked', 'true');
    });
    $(this).parent().append(icon);
});

我使用<a>的原因是因为IE会正确地尊重:hover CSS伪类。同样在那个音符上,我正在使用CSS spriting,所以你将灰色和全彩色图像组合成一个40px高的图像,顶部是灰色版本。

<a>的css看起来像是:

a.icon {
    float: left;

    /* width and height of your weather icons */
    width: 20px;
    height: 20px;

    background-repeat: no-repeat;
    background-position: 0 0;
}

a.selected,
a:hover.icon {
    background-position: 0 -20px;
}

.sunny{
    background-image: url(sunny.png);
}

.rainy {
    background-image: url(rainy.png);
}

/* remaining weather styles */ 

您可以使用背景颜色in action here查看版本。