And ... one solution that I can think of is to replace the selection with the ul object and attach the event handlers to the synchronization selection in ul. Calling .offset () on li elements works as expected on both FF and Chrome.
So, if you click li elements, it will update its background color and update the selected hidden selection value. That way, when the form is submitted, the correct value is submitted.
http://jsfiddle.net/hqYqh/
HTML:
<select id="mySelect" multiple="true"> <option>2011</option> <option>2012</option> <option>2013</option> <option>2014</option> <option>2015</option> <option>2016</option> <option>2017</option> <option>2018</option> <option>2019</option> </select>
CSS
ul.select { display: inline-block; border: 1px solid black; list-style: none; margin: 0; padding: 2px; height: 80px; overflow: auto; width: 50px; } ul.select li { background-color: none; cursor: pointer; } ul.select li.selected { background-color: skyblue; }
JS:
var $select = $('#mySelect'); var $ul = $('<ul class="select">').on('click', 'li', function() { $(this).parent().find('li').removeClass('selected'); $(this).addClass('selected'); $select.val($(this).text()).change(); }); $select.find('option').each(function() { var $li = $('<li>').text($(this).text()); $ul.append($li); }); $select.hide().after($ul); $select.change(function() { alert('Offset of ' + $(this).val() + ' is ' + JSON.stringify($('li.selected').offset())); });
EDITED
So, I tried another method after the Huangism clause using offset () and scrollTop () of the select element.
The only thing that is not available is the height of the option element. So I tried to estimate the font size, but it was not perfect, and I had to add magic number 3 in Chrome to get exact offsets. If you can determine the height of the option element, you do not need to deal with the whole ul / li business above.
Here he is:
http://jsfiddle.net/hqYqh/2/
optionOffset = function($option) { var i = $option.index(); var h = Number($option.css('font-size').replace(/px/, '')) + 3; // Cannot get the height of the option element :( var $select = $option.parent(); var offset = $select.offset(); offset.top += i*h - $select.scrollTop(); return offset; }
haejeong87
source share