Jquery 铬';s offset()为选项返回空值
我无法计算select中选项的偏移位置:Jquery 铬';s offset()为选项返回空值,jquery,google-chrome,firefox,Jquery,Google Chrome,Firefox,我无法计算select中选项的偏移位置: <select multiple="true"> <option>asdf</option> <option id="bar">qwer</option> </select> $("#bar").offset() FF返回: {top: 26, left: 9} 我需要像FF returns这样的职位。Chrome有解决办法吗 我想说chrome返回0,因为该选
<select multiple="true">
<option>asdf</option>
<option id="bar">qwer</option>
</select>
$("#bar").offset()
FF返回:
{top: 26, left: 9}
我需要像FF returns这样的职位。Chrome有解决办法吗
我想说chrome返回0,因为该选项不可见,所以它无法计算顶部。这也可能发生在safari中,因为它都是webkit浏览器。
我能想到的唯一一件事是你得到选择的偏移顶部,然后进行一些计算,得到选项的近似顶部。例如,如果一个选项的高度约为10px,您需要知道在所需选项之前有多少个选项,并计算出需要添加到所选顶部的像素数。啊。。。我能想到的一个解决方案是用ul对象替换select,并附加事件处理程序将select同步到ul。在li元素上调用.offset()在FF和Chrome上都能正常工作 因此,如果单击li元素,它将更新其背景色并更新隐藏选择的选定值。这样,在提交表单时,将发送正确的值 HTML: JS:
可能会有帮助。我不知道,但chrome中的
选项元素可能没有偏移量。你能告诉我们一些人可能会想出另一种不涉及的方法的想法吗。偏移量()
选择的偏移量不够好吗?我认为这是一个很好的解决方案,但我认为这取决于兼容性要求(移动设备),如果这真的是一个有效的解决方案,那就好了。它应该可以在移动设备上工作,但不会触发设备的本机UI。您可以根据USER_AGENT头字符串的内容执行此代码。如果你能告诉我为什么你首先需要选择权的抵消,也许我可以进一步帮助你。我在采纳了黄氏的建议后,添加了第二种可能的解决方案。这可能对你有用。@crudolph你已经接受了这个答案,也许你可以解释一下答案的哪一部分对你有用?也许可以详细说明你的原始问题,这样我们就可以了解为什么,并可能给出一个更好的答案?
{top: 26, left: 9}
<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>
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;
}
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()));
});
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;
}