开发者

Javascript control of SELECT scrolling

开发者 https://www.devze.com 2023-01-31 15:47 出处:网络
Firstly, I am no Javascript expert. I\'d like to add a feature to a SELECT box I am using which automatically scrolls to the end when a new item is added, but only if the user has not scrolled up.

Firstly, I am no Javascript expert. I'd like to add a feature to a SELECT box I am using which automatically scrolls to the end when a new item is added, but only if the user has not scrolled up.

Basically, when a user is revie开发者_JS百科wing older entries, I don't want new arrivals to snap the position to the end of the select list. However, if the user scrolls down to the bottom using the scroll bar, new arrivals shoudl automatically be brought into view.

Here is what I have so far

<script type="text/javascript">
  function AddItem(s) 
  {
    document.getElementById('content').add(new Option(s));
    // Scroll to end - cant remember why I am using this pair of commands :)
    document.getElementById('content').selectedIndex = document.getElementById('content').length - 1;
    document.getElementById('content').selectedIndex = document.getElementById('content').length + 1;
  }
</script>

I am expecting to have to perform a test to see if the last but one item is visible. If so, we are at the bottom and should perform the autoscroll. Is this correct?

Thanks JS Masters

Simon


The scroll bar of a select box isn't accessible via javascript so I don't think you'll be able to do this.

related: Height of an HTML select box (dropdown)

You can see which items are selected and change the selection but I don't think there's any way to tell which items are visible.


As @bemace noted, JavaScript does not provide access to scroll the select box. The best you can do is "pre-select" the item... which, if this is a "dropdown" style select, should show that option.

e.g.

<script type="text/javascript">
  function AddItem(s){
    var mySelect = document.getElementById('content');
    mySelect.add(new Option(s));
    mySelect.selectedIndex = mySelect.options.length - 1;
  }
</script>

It should be noted though, if you have 30 options in the select, and the size attribute is set to say 10 (e.g. it shows as a list, not a dropdown), then when you "choose" the new (31st option), the list won't necessarily scroll to show that entry

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号