Chr*_*ris 8 firefox jquery google-chrome
我无法计算选择中选项的偏移位置:
<select multiple="true">
<option>asdf</option>
<option id="bar">qwer</option>
</select>
$("#bar").offset()
Run Code Online (Sandbox Code Playgroud)
Chrome返回(任何jQuery版本,如1.7.2,1.9测试):
{top: 0, left: 0}
Run Code Online (Sandbox Code Playgroud)
FF返回:
{top: 26, left: 9}
Run Code Online (Sandbox Code Playgroud)
我需要像FF回归这样的位置.Chrome有解决方法吗?
啊...我能想到的一个解决方案是用 ul 对象替换 select,并附加事件处理程序以将 select 同步到 ul。在 li 元素上调用 .offset() 在 FF 和 Chrome 上都能按预期工作。
因此,如果单击 li 元素,它将更新其背景颜色并更新隐藏选择的选定值。这样,当提交表单时,会发送正确的值。
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>
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
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()));
});
Run Code Online (Sandbox Code Playgroud)
因此,我按照Huangism的建议尝试了另一种方法,使用选择元素的offset()和scrollTop()。
唯一不可用的是选项元素的高度。所以我尝试使用 font-size 进行估计,但它并不完美,我必须在 Chrome 上添加幻数 3 才能获得准确的偏移量。如果你能算出option元素的高度,就不用处理上面所有的ul/li业务了。
这里是:
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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
912 次 |
| 最近记录: |