JavaScript get position of option element?

蓝咒 提交于 2019-12-10 16:13:17

问题


I have a web app that needs to know the position (x/y not index!) of an option element inside a multi select list. It works great in Firefox but no dice in Chrome or IE.

Is it possible to get an option's position in Chrome/IE with JavaScript?

Here is my fiddle displaying the issue: http://jsfiddle.net/jamiller619/Kbh4g/3/ Works with Firefox but not in IE/Chrome.


回答1:


Short answer - you can't (webkit issue).

But you can cheat!!!

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);
    });
});

It's a quick and dirty solution!

UPDATE

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);
    });
});


来源:https://stackoverflow.com/questions/9948885/javascript-get-position-of-option-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!