代码之家  ›  专栏  ›  技术社区  ›  Drew Noakes

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

  •  2
  • Drew Noakes  · 技术社区  · 14 年前

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

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

    我已经找到了大量的jquery分级控件,它们提供了这个功能,但是没有什么能完全满足我的需要(可能是因为我不知道它的名字,因此无法通过谷歌搜索)。

    哦,如果用户没有启用javascript,它应该很好地降级以提供标准 <选择& <广播电台; 选项。

    1 回复  |  直到 13 年前
        1
  •  3
  •   Pat    14 年前

    你可以很容易地自己滚。从这样的标记开始:

    <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 & GT; 是因为我会适当地尊重 :hover CSS伪类。另外,我使用的是CSS Spriting,所以你可以将你的灰色和全彩图像组合成一个40px高的图像,灰色的图像在顶部。

    的CSS <A & GT; 看起来像:

    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 .