Use JavaScript to beautify the HTML select tag's drop-down list effect _javascript tips

Source: Internet
Author: User
Tags generator


First, take a look at the use of the Select label by an example:

And then the effect is generally like this:






Both beauty and ugliness are for the moment. The select in all HTML elements is one of the more pit daddies. The main point of his maddening place is:

Different browsers display default Drop-down boxes that don't look exactly the same
IE cannot manually set the height of the select (this is the most pit Dad!) ), can only rely on Font-size prop up
The drop-down arrow on the right side of the select cannot be removed using the background, which makes it impossible to beautify with CSS
To sum up, the main solutions are:



Hide a Select, and use DIV to simulate
Set select transparency to 0, and then use relative positioning to add a div that looks much like select and beautify.


The general principle of

Hiding scenarios is as follows:
Find the Select that the page needs to work with, hide it
According to option of Select, create an Li list (of course, it can also be div) and hide it.
creates a div in the location of the select that displays the value of the Select (option selected). and use CSS to beautify it so that it looks like a select
Add event so that when you click "Select", the list of Li is displayed. and using relative positioning, let this list appear under "Select"
Add events to the Li list, simulate the selection process of the Drop-down box (click event and keyboard ↑↓ events to simulate)
when the selection is complete, the selected value is displayed to the top of select. and set the value of the real select
Of course, if you want to do more complex points, you can also add option search, multiple selection, multiple selections after the deletion of options. At that time the general principle is similar to the above. There are many such plug-ins on the web. However, the use of online plug-ins to test the compatibility of the browser, the more complex function of the simulation select, the more incompatible with the compatibility of
 
If your program does not need a complex Select, the second option to set transparency may be appropriate for you. This is also the plan to share with you today.
It works as follows:
 
 
finds the current page's select and sets its transparency to 0. Makes it invisible, but you can click and select values
Create a div, use relative positioning, and place it below the Select, and through CSS control to make it look like a select. Why must it be placed below? Because of this, we can click on the real select, and the user looks like the emulated select of the click, because the real select is completely transparent. If placed above, the user clicks on the emulated select, and the real select does not expand!!!
Set div text to select value
to add the event so that after the true select value, the value is displayed on the mock div
 
 
First code:
 


 

(function ($) {
var selectFix = function () {
var select = $ (this);
// Set the transparency to 0. Of course, you can also use css to control. Use Jquery to set the transparency to shield the transparency. Browser compatibility issues.
$ (select) .css ({
"opacity": 0
});
// Find the selected option
var sOptions = this .get (0) .options;
// Set the value of the simulated select
var setFixDivText = function (selectValue) {
var text = "";
for (var i = 0; i <sOptions.length; i ++) {
var option = sOptions [i];
if (option.value == selectValue) {
text = $ (option) .text ();
break;
}
}
return text;
};
// Simulated selection
// Pass the value of select during initialization
var selectFixDiv = $ ('<div id = "J_selectFix_' + select.attr (" id ") + '" class = "selectFix">' + setFixDivText ($ (select) .val ()) + '</ div> ');
select.after (selectFixDiv);
var left = $ (select) .offset (). left;
var top = $ (select) .offset (). top-1; // Because the general selection has a 1px border, so it is pulled up 1px here
$ (selectFixDiv) .css ({
"top": top,
"left": left
});
// When selecting a value, the value is displayed on the simulated select
$ (select) .bind ("change click", function () {
$ (selectFixDiv) .text (setFixDivText ($ (this) .val ()));
});
};
$ .fn.selectFix = selectFix;
}) (jQuery);
(function ($) {
  var selectFix = function () {
    var select = $ (this);
    // Set the transparency to 0. Of course, you can also use css to control. Use Jquery to set the transparency to shield the transparency. Browser compatibility issues.
    $ (select) .css ({
      "opacity": 0
    });
    // Find the selected option
    var sOptions = this.get (0) .options;
    // Set the value of the simulated select
    var setFixDivText = function (selectValue) {
      var text = "";
      for (var i = 0; i <sOptions.length; i ++) {
        var option = sOptions [i];
        if (option.value == selectValue) {
          text = $ (option) .text ();
          break;
        }
      }
      return text;
    };
 
    // Simulated selection
    // Pass the value of select during initialization
    var selectFixDiv = $ ('<div id = "J_selectFix _' + select.attr (" id ") + '" class = "selectFix">' + setFixDivText ($ (select) .val ()) + '</ div> ');
    select.after (selectFixDiv);
 
    var left = $ (select) .offset (). left;
    var top = $ (select) .offset (). top-1; // Because the general selection has a 1px border, so here is 1px
    $ (selectFixDiv) .css ({
      "top": top,
      "left": left
    });
     
    // When selecting a value, the value is displayed on the simulated select
    $ (select) .bind ("change click", function () {
      $ (selectFixDiv) .text (setFixDivText ($ (this) .val ()));
    });
  };
  $ .fn.selectFix = selectFix;
}) (jQuery);



Plug-in code run:


JQuery (document). Ready (function () {
var selects=$ ("Select.selectinput");
if (selects.length) {
Selects.each (function () {
$ (this). Selectfix ();
});
}
});

JQuery (document). Ready (function () { 
  var selects=$ ("Select.selectinput"); 
  if (selects.length) { 
    Selects.each (function () { 
      $ (this). Selectfix (); 
    }); 
  } 
}); 


Here is the HTML code:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
< HTML >
< HEAD >
< TITLE > New Document </ TITLE >
< META NAME = "Generator" CONTENT = "EditPlus" >
< META NAME = "Author" CONTENT = "" >
< META NAME = "Keywords" CONTENT = "" >
< META NAME = "Description" CONTENT = "" >
< script type = text /javascript src = "http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js" > </ script >
< script type = text /javascript src = "temp.js" > </ script >
< style >
html {font-family: "宋体";font-size: 12px;line-height: 25px;color: #6F6F6F;}
.dn {display: none;}
select{cursor: pointer;}
input,
select,
textarea,
.selectFix {background: white;border: 1px solid #E0E0E0;hide-focus: expression( this.hideFocus = true ); outline: none;}
.formText,
.selectInput,
.text,
.selectFix{border: 1px solid #CCC;width: 180px;height: 30px;line-height:30px;padding: 0 3px;}
.selectInput {width: 248px; font-size:13px; position: relative; z-index: 2;}
.selectFix{width:248px; background: url(selectBg.png) no-repeat; background-position: right; background-color: #fff; position:absolute; z-index: 1;}
</ style >
</ HEAD >
< BODY >
< div id = "main" >
< select id = "sex" class = "selectInput" name = "sex" >
< option value = "0" > 男 </ option >
< option value = "1" > 女 </ option >
</ select >
</ div >
</ BODY >
</ HTML >

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 
<HTML> 
<HEAD> 
<TITLE> New Document </TITLE> 
<META NAME="Generator" CONTENT="EditPlus"> 
<META NAME="Author" CONTENT=""> 
<META NAME="Keywords" CONTENT=""> 
<META NAME="Description" CONTENT=""> 
 <script type=text/javascript src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script> 
 <script type=text/javascript src="temp.js"></script> 
 
 <style> 
html {font-family: "宋体";font-size: 12px;line-height: 25px;color: #6F6F6F;} 
.dn {display: none;} 
select{cursor: pointer;} 
input, 
select, 
textarea, 
.selectFix {background: white;border: 1px solid #E0E0E0;hide-focus: expression(this.hideFocus=true); outline: none;} 
.formText, 
.selectInput, 
.text, 
.selectFix{border: 1px solid #CCC;width: 180px;height: 30px;line-height:30px;padding: 0 3px;} 
.selectInput {width: 248px; font-size:13px; position: relative; z-index: 2;} 
.selectFix{width:248px; background: url(selectBg.png) no-repeat; background-position: right; background-color: #fff; position:absolute; z-index: 1;} 
 </style> 
</HEAD> 
 
<BODY> 
<div id="main"> 
  <select id="sex" class="selectInput" name="sex"> 
    <option value="0">男</option> 
    <option value="1">女</option> 
  </select> 
</div> 
</BODY> 
</HTML> 


Compatible with mainstream browsers.


But there is also a major flaw, in the old version of IE, the real select height can not be stretched. So, the user clicks on the bottom position of the emulated select to find that the Select cannot be expanded!!
But the art of design is balance, and if you can't stand the flaw, you can use the first solution.


Also, after testing, if the select is in a hidden container, then the location of the Select is blank!!
What the hell is going on here?!
Originally, the HTML element was hidden and could not get his screen coordinates!!! So this shows that the real select is completely transparent, and the emulated select runs to the top left corner of the screen. Because he gets the coordinates of the Select (0,0)


Don't worry, this problem has the following solution:
1, separate write code to trigger select beautification program
First, you need to make the following modifications to the above landscaping program:


JQuery (document). Ready (function () {
var selects=$ ("Select.selectinput");
if (selects.length) {
Selects.each (function () {
if (! $ (this). attr ("autoFix") = = "false") {
$ (this). Selectfix ();
}
});
}
);

JQuery (document). Ready (function () { 
  var selects=$ ("Select.selectinput"); 
  if (selects.length) { 
    Selects.each (function () { 
      if (! $ (this). attr ("autoFix") = = "false") { 
        $ (this). Selectfix (); 
      } 
    }); 
  } 
); 


Then, add the attribute autofix= "false" on the hidden Select:


< SELECT id = "Sex" class = "selectinput" name = "Sex" AutoFix = "false" >
< option value = "0" > Male </ Option >
< option value = "1" > Female </option >
</select >

<select id= "Sex" class= "Sele" Ctinput "name=" Sex "autofix=" false "> 
    <option value=" 0 "> Male </option> 
    <option value=" 1 "> Female </option> 
  </select> 


Then, manually call $ ("#sex") when the outer container is displayed. Selectfix ()

2, if the container display or hidden is the third party plug-in control, modify inconvenient can consider the following scheme:
In the beautification program, first determine whether select is hidden, if not the logic does not change, if hidden, then add a timer, loop to determine whether the element is displayed, and then automatically call fix when it is displayed, and then remove the timer
The code is as follows:


// Add the operation of hiding the selection
(function ($) {
var selectFix = function () {
var select = $ (this);
// Set the transparency to 0. Of course, you can also use css to control. Use Jquery to set the transparency to shield the transparency. Browser compatibility issues.
$ (select) .css ({
"opacity": 0
});
if (! select.is (": hidden")) {
var sOptions = this .get (0) .options;
var setFixDivText = function (selectValue) {
var text = "";
for (var i = 0; i <sOptions.length; i ++) {
var option = sOptions [i];
if (option.value == selectValue) {
text = $ (option) .text ();
break;
}
}
return text;
};
var selectFixDiv = $ ('<div id = "J_selectFix_' + select.attr (" id ") + '" class = "selectFix" status = "close">' + setFixDivText ($ (select) .val ()) + '</ div>');
select.after (selectFixDiv);
var selectWidth = $ (select) .innerWidth ();
var selectFixDivWidth = $ (selectFixDiv) .innerWidth ();
var left = $ (select) .offset (). left;
var top = $ (select) .offset (). top-1;
$ (selectFixDiv) .css ({
"top": top,
"left": left,
"margin": 0
});
$ (select) .bind ("change click", function () {
$ (selectFixDiv) .text (setFixDivText ($ (this) .val ()));
});
} else {
var tasks = function () {
if (! $ (select) .is (": hidden")) {
$ (select) .selectFix ();
clearInterval (timer);
}
};
var timer = setInterval (tasks, 500)
}
};
$ .fn.selectFix = selectFix;
}) (jQuery);
// Add the operation of hiding the selection
(function ($) {
  var selectFix = function () {
    var select = $ (this);
    // Set the transparency to 0. Of course, you can also use css to control. Use Jquery to set the transparency to shield the transparency. Browser compatibility issues.
    $ (select) .css ({
      "opacity": 0
    });
 
    if (! select.is (": hidden")) {
      var sOptions = this.get (0) .options;
 
      var setFixDivText = function (selectValue) {
        var text = "";
        for (var i = 0; i <sOptions.length; i ++) {
          var option = sOptions [i];
          if (option.value == selectValue) {
            text = $ (option) .text ();
            break;
          }
        }
        return text;
      };
 
      var selectFixDiv = $ ('<div id = "J_selectFix _' + select.attr (" id ") + '" class = "selectFix" status = "close">' + setFixDivText ($ (select) .val ()) + '</ div>');
      select.after (selectFixDiv);
 
      var selectWidth = $ (select) .innerWidth ();
      var selectFixDivWidth = $ (selectFixDiv) .innerWidth ();
      var left = $ (select) .offset (). left;
 
      var top = $ (select) .offset (). top-1;
      $ (selectFixDiv) .css ({
        "top": top,
        "left": left,
        "margin": 0
      });
 
      $ (select) .bind ("change click", function () {
        $ (selectFixDiv) .text (setFixDivText ($ (this) .val ()));
      });
    } else {
      var tasks = function () {
        if (! $ (select) .is (": hidden")) {
          $ (select) .selectFix ();
          clearInterval (timer);
        }
      };
      var timer = setInterval (tasks, 500)
    }
  };
  $ .fn.selectFix = selectFix;
}) (jQuery); 
 

The

Runs the code unchanged from the original.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.