如何在我的样式选择下拉菜单中模拟键盘行为? [英] How do I mimic keyboard behavior in my styled select dropdown?

查看:163
本文介绍了如何在我的样式选择下拉菜单中模拟键盘行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jQuery 1.11。我想给我的选择下拉式样,因为,让我们面对它,默认看起来很烂。所以我找到一些样式

I’m using jQuery 1.11. I want to style my select drop-downs because, let’s face it, the default looks sucks. So I found some styles

.selectMenu {
  font-family: 'Oxygen', sans-serif;
  font-size: 20px;
  height: 50px;
  -webkit-appearance: menulist-button;
}

.select-hidden {
  display: none;
  visibility: hidden;
  padding-right: 10px;
}

.select {
  cursor: pointer;
  display: inline-block;
  position: relative;
  font-size: 16px;
  color: #fff;
  width: 220px;
  height: 42px;
}

.select-styled {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-color: gray;
  padding: 11px 12px;
  -webkit-transition: all 0.2s ease-in;
  transition: all 0.2s ease-in;
}
.select-styled:after {
  content: "";
  width: 0;
  height: 0;
  border: 7px solid transparent;
  border-color: #fff transparent transparent transparent;
  position: absolute;
  top: 16px;
  right: 10px;
}
.select-styled:hover {
  background-color: #7b7b7b;
}
.select-styled:active, .select-styled.active {
  background-color: #737373;
}
.select-styled:active:after, .select-styled.active:after {
  top: 9px;
  border-color: transparent transparent #fff transparent;
}

.select-options {
  display: none;
  position: absolute;
  top: 100%;
  right: 0;
  left: 0;
  z-index: 999;
  margin: 0;
  padding: 0;
  list-style: none;
  background-color: #737373;
  overflow: scroll;
}
.select-options li {
  margin: 0;
  padding: 12px 0;
  text-indent: 15px;
  border-top: 1px solid #676767;
  -webkit-transition: all 0.15s ease-in;
  transition: all 0.15s ease-in;
}
.select-options li:hover {
  color: gray;
  background: #fff;
}
.select-options li[rel="hide"] {
  display: none;
}

ul.select-options {
  max-height: 15em;
  overflow-y: scroll;
  overflow-x: hidden;
}

并添加了此jQuery

and added this jQuery

$(function() {

        $('select').each(function(){
            styleSelectMenu($(this));
        });

});

// This method applies the styles to our select menu
function styleSelectMenu(selectMenu)
{
    var $this = $(selectMenu), numberOfOptions = $(selectMenu).children('option').length;

                /*** NEW - start ***/
                var $paddingCalculator = $('<div />', {
                'class' : "select-styled test"
    }).css({
                width : 0,
        visibility : "hidden"
    }).appendTo("body");
    $this.addClass('select-hidden');
    var paddingWidth = $paddingCalculator.outerWidth() + 10;
    $paddingCalculator.remove();

    //var selectWidth = $this.width() + paddingWidth;
    var selectWidth = $this.outerWidth() + paddingWidth;
    //alert(selectWidth);

    if ( !$this.parent().hasClass('select') ) {
                var $wrapper = $("<div />", {
                        'class' : "select"
        }).css({
                        width   : selectWidth
        });
        $this.wrap( $wrapper );
    }   // if

                /*** NEW - end ***/

    if ( !$this.next().hasClass('select-styled') ) {
        $this.after('<div class="select-styled"></div>');
    }    // if

    var $styledSelect = $this.next('div.select-styled');
    $styledSelect.text($this.children('option').eq(0).text());

    if ( $styledSelect.parent().find('ul').length > 0 ) {
        $styledSelect.parent().find('ul').remove();
    }   // if
    var $list = $('<ul />', {
        'class': 'select-options'
    }).insertAfter($styledSelect);

    for (var i = 0; i < numberOfOptions; i++) {
        $('<li />', {
            text: $this.children('option').eq(i).text(),
            rel: $this.children('option').eq(i).val()
        }).appendTo($list);
    }

    var $listItems = $list.children('li');

    // This is the event when someone opens the list
    $styledSelect.unbind('click')
    $styledSelect.click(function(e) {
        e.stopPropagation();
        $('div.select-styled.active').each(function(){
            $(this).removeClass('active').next('ul.select-options').hide();
        });
        $(this).toggleClass('active').next('ul.select-options').toggle();
    });

    // This is the event when someone actually selects something from the list
    $listItems.unbind('click.selectStyledItem')
    $listItems.bind('click.selectStyledItem', function(event) {
         clickListItem(event, $styledSelect, $this, $(this), $list);
    });

    $(document).click(function(event) {
        $styledSelect.removeClass('active');
        $list.hide();
    });


    var selectedIndex = $this[0].selectedIndex;
    if (selectedIndex > 0) {
        var name = $this.attr("name")
        var selectedText = $( "select[name='" + name + "'] option:selected" ).text();
        selectItemFromStyledList($styledSelect, $this, selectedText, $list);
    }   // if

}

// This is the method that will select an item from the styled list
function selectItemFromStyledList(styledSelect, selectMenu, selectedText, listToHide)
{
    $(styledSelect).text(selectedText).removeClass('active');
    $(selectMenu).val($(selectMenu).attr('rel'));
    $(listToHide).hide();
    // Select option in the underlying list so that the form gets submitted
    // with the right values
    selectedOption = $(selectMenu).find("option").filter(function () { return $(this).html() == selectedText; });
    $(selectMenu).find("option[selected='selected']").removeAttr("selected");
    $(selectedOption).attr("selected","selected");
}       // selectItemFromStyledList

function clickListItem(event, styledSelect, selectMenu, listItemClicked, list)
{
        var $styledSelect = $(styledSelect);
        var $selectMenu = $(selectMenu);
        var $listItem = $(listItemClicked);
        var $list = $(list);

        event.stopPropagation();
        var selectedText = $listItem.text();
        selectItemFromStyledList($styledSelect, $selectMenu, selectedText, $list)
 }       // clickListItem


$ b b

这里显示的小提琴就在这里 - http://jsfiddle.net/cwzjL2uw/1/。问题是,虽然我已经实现了风格,我没有复制正常的选择菜单的键盘行为。我的问题是,如何使我的菜单的行为,当我单击字母A,第一个A项目被选择(在这种情况下,阿拉巴马州),就像一个普通的选择菜单行为。

The Fiddle illustrating this is here — http://jsfiddle.net/cwzjL2uw/1/ . The issue is, although I have achieved the style, I have failed to replicate the keyboard behavior that a normal select menu has. My question is, how can I make my menu behave such that when I click the letter "A," the first "A" item is selected (in this case "Alabama"), just like a regular select menu behaves.

推荐答案

这里是一个如何使用代码实现这个例子。通过侦听您的活动下拉列表中的键,并迭代查找和滚动到匹配的选项。

Here is an example of how you can accomplish this using your code. By listening for keys on your active drop down and iterating through the options to find and scroll to a match.

function styleSelectMenu(selectMenu)
{    
    .......

    $(document).click(function(event) {
        $styledSelect.removeClass('active');
        $list.hide();
    });


    //Example

    var keyUps = "", timeOut, $selectOptions = $('.select-options'); 
    $(document).keyup(function(event){
      if(!$selectOptions.prev().hasClass('active')){
        return false;
      }
      if(event.key){
      keyUps += event.key;
      retrieveFromOptions($selectOptions,keyUps);
    }
    clearTimeout(timeOut);
    timeOut = setTimeout(function(){
      keyUps = "";
    },250);

   .......

});

function retrieveFromOptions($options,val){
   $options.find('li').each(function(index){
    if(this.textContent.substring(0,val.length).toLowerCase() === val.toLowerCase()){
        $options.scrollTop(43*index);
        return false;
    }
   });
}

小提琴

请注意,此解决方案不会实现等效于将鼠标悬停在项上的选择效果。这可以做,但需要更多的工作。

Notice that this solution does not implement a selection effect equivalent to hovering over the items. That could be done but would require more work.

我建议使用一个解决方案,如ConnorsFan或一个只有CSS用于样式的select元素而不替换它。这样,您将保留本机功能。

I would recommend using a solution such as ConnorsFan or one where only css is used to style the select element without replacing it. That way you will retain native functionality.

有许多CSS框架可以实现select元素的样式。

There are many CSS frameworks which implement the styling of the select element.

Bootstrap 就是一个例子。

这篇关于如何在我的样式选择下拉菜单中模拟键盘行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆