我有一个网络应用程序,需要知道多选列表中的选项元素的位置(x / y而不是索引!)。它在Firefox中运行良好,但在Chrome或IE中没有骰子。
是否可以通过JavaScript在Chrome / IE中获得选项的位置?
这是我的小提示,显示问题:http://jsfiddle.net/jamiller619/Kbh4g/3/适用于Firefox但不适用于IE / Chrome。
答案 0 :(得分:2)
简短回答 - 你不能(webkit问题)。
但你可以作弊!!!
HTML:
<div style="position:relative">
<select multiple="multiple">
<option>Test 1</option>
<option>Test 2</option>
<option>Test 3</option>
<option>Test 4</option>
<option>Test 5</option>
<option>Test 6</option>
<option>Test 7</option>
<option>Test 8</option>
<option>Test 9</option>
<option>Test 10</option>
</select>
</div>
<br />
option position:<br />
Left: <span id="pos-x"></span><br />
Top: <span id="pos-y"></span>
CSS:
select
{
font-size:20px;
}
JQuery的:
$(function()
{
$('select').change(function() {
var optionHeight = 20; // or get this value from the stylesheet or inline-style
var textIndent = 1; // best guess or work it out using coordinate crosshair tool
$('#pos-y').text((this.selectedIndex + 1) * optionHeight);
$('#pos-x').text(this.offsetLeft + textIndent);
});
});
这是一个快速而肮脏的解决方案!
更新
CSS:
select
{
height: 150px;
font-size: 20px;
}
JQuery的:
$(function()
{
$('select').change(function() {
var fontSize = 20; // or get this value from the stylesheet or inline-style
var lineHeight = fontSize + 4 // need a better calculation here
var optionHeight = lineHeight;
var textIndent = 1; // best guess or work it out using coordinate crosshair tool
var top = (this.selectedIndex * optionHeight) - this.scrollTop;
$('#pos-y').text(top);
$('#pos-x').text(this.offsetLeft + textIndent);
});
});