Home >Web Front-end >CSS Tutorial >How to Make HTML Select Box Options Visible on Hover?

How to Make HTML Select Box Options Visible on Hover?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 20:14:031063browse

How to Make HTML Select Box Options Visible on Hover?

HTML Select Box Options Visible on Hover

This query discusses the creation of a select box where the options are visible on hover instead of clicking. To achieve this effect, you can implement the following approach.

jQuery Manipulation

<code class="js">$('#selectUl li:not(":first")').addClass('unselected'); // Hide unselected elements

$('#selectUl').hover(
  function() { // Mouseover event
    $(this).find('li').click(
      function() {
        $('.unselected').removeClass('unselected'); // Remove unselected styles

        $(this).siblings('li').addClass('unselected'); // Add unselected styles to other elements

        var index = $(this).index(); // Get the index of the clicked option
        $('select option:selected').removeAttr('selected'); // Deselect the previously chosen option

        $('select[name=size]')
          .find('option:eq(' + index + ')')
          .attr('selected', true); // Select the new option
      }
    );
  },
  function() { // Mouseout event
    // Hide unselected elements
  }
);</code>

CSS Styling

To style the select box, you can use the following CSS:

<code class="css">select {
  opacity: 0.5;
}
ul {
  width: 8em;
  line-height: 2em;
}

li {
  display: list-item;
  width: 100%;
  height: 2em;
  border: 1px solid #ccc;
  border-top-width: 0;
  text-indent: 1em;
  background-color: #f90;
}
li:first-child {
  border-top-width: 1px;
}

li.unselected {
  display: none;
  background-color: #fff;
}
ul#selectUl:hover li.unselected {
  background-color: #fff;
}
ul#selectUl:hover li,
ul#selectUl:hover li.unselected {
  display: list-item;
}
ul#selectUl:hover li {
  background-color: #fc0;
}
ul#selectUl li:hover,
ul#selectUl li.unselected:hover {
  background-color: #f90;
}</code>

Plug-In Approach

An alternative approach is to use a simple plug-in:

<code class="js">(function($) {
  $.fn.selectUl = function() {
    // ... code goes here ...
    return $(this);
  };
})(jQuery);

$('#sizes').selectUl();</code>

The above is the detailed content of How to Make HTML Select Box Options Visible on Hover?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn