文章

My attempt to IE6/7 select box width

In IE6/7, when you set the width of a <select> element, it will chop off the option text. It’s an age-old question but I would like to record my attempt to this problem:

  • create an inline block to wrap the <select> up
  • set width and height of the inline block the same as the original select
  • set position ‘relative’ for inline block
  • set position ‘absolute’ for <select>
  • when mouse over, set <select> width as ‘auto’
  • when mouse click, toggle a flag ‘clicked’ (using $.data)
  • when mouse out and flagged as ‘clicked’, reset <select> width
  • when blur or change, reset <select> width

The reason for wrapping an inline block is that when <select> set/reset width, it would not affect the layout of other elements.

The ‘clicked’ flag is used to indicate if the <select> is ‘expanded’. If it is, the mouseout event should not reset the width.

Here is the code (and of course only effective in IE6/7):

*