Home >Web Front-end >JS Tutorial >Use JavaScript to beautify the drop-down list effect of HTML select tag_javascript skills
First, let’s review the usage of the select tag through an example:
<html> <body> <form> <select name="cars"> <option value="volvo">Volvo</option> <option value="saab">Saab</option> <option value="fiat">Fiat</option> <option value="audi">Audi</option> </select> </form> </body> </html>
Then the normal effect is like this:
Leave aside beauty and ugliness for the moment...select is one of the more deceptive elements among all html elements. The main things that make him crazy are:
The default drop-down boxes displayed by different browsers are not exactly the same
You cannot manually set the height of the select under IE (this is the most annoying thing!), you can only rely on font-size to support it
The drop-down arrow on the right side of select cannot be background removed, which makes it impossible to use css for beautification
To sum up, the main solutions are:
Hide the select and use div to simulate it
Set the select transparency to 0, and then use relative positioning to add a div that looks like select and is beautified below
The general principle of the hiding scheme is as follows:
Find the selection that needs to be processed on the page and hide it
According to the selected option, create a li list (of course it can also be a div) and hide it.
Create a div at the select position to display the selected value (selected option). and beautify it using css to make it look like a select
Add an event to display the li list when "select" is clicked. And use relative positioning to make this list appear below "select"
Add events to the li list to simulate the value selection process of the drop-down box (click events and keyboard ↑↓ events must be simulated)
After the value selection is completed, the selected value should be displayed in the "select" above and the real select value should be set
Of course, if you want to make it more complicated, you can also add option search, multiple selection, option deletion after multiple selection, etc. At that time, the general principles were similar to the above. There are many such plug-ins on the Internet. But when using online plug-ins, you should pay attention to testing the compatibility of the browser. The more complex the function is to simulate the selection, the harder it is to achieve compatibility
If your program does not require such complex selections, then the second option of setting transparency may be suitable for you. What I want to share with you today is also this plan.
Its principle is as follows:
Find the select of the current page and set its transparency to 0. Make it invisible, but you can click and select the value
Create a div, use relative positioning, place it below the select, and control it with css to make it look like a select. Why does it have to be placed below? Because of this, we can click on the real select and it will look like the user clicked on the simulated select because the real select is completely transparent. If it is placed above, the user clicks on this simulated select, and the real select will not expand! ! !
Set the text of the div to the value of select
Add an event so that after the real select selects the value, the value is displayed on the simulated div
Let’s start with the code:
( function ($){ var selectFix= function (){ var select=$( this ); //设置透明度为0 当然你也可以使用css控制 使用Jquery设置透明度可以屏蔽 透明度的 浏览器兼容性问题 $(select).css({ "opacity" :0 }); //找到select的选项 var sOptions= this .get(0).options; //设置模拟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; }; //模拟的select //初始化时要将select的值传入 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; //因为一般select都有1px的边框,所以这里往上拉1px $(selectFixDiv).css({ "top" : top, "left" : left }); //select选值时,将值显示到模拟的select上 $(select).bind( "change click" , function (){ $(selectFixDiv).text(setFixDivText($( this ).val())); }); }; $.fn.selectFix=selectFix; })(jQuery);
(function($){ var selectFix=function(){ var select=$(this); //设置透明度为0 当然你也可以使用css控制 使用Jquery设置透明度可以屏蔽 透明度的 浏览器兼容性问题 $(select).css({ "opacity":0 }); //找到select的选项 var sOptions=this.get(0).options; //设置模拟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; }; //模拟的select //初始化时要将select的值传入 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;//因为一般select都有1px的边框,所以这里往上拉1px $(selectFixDiv).css({ "top" : top, "left" : left }); //select选值时,将值显示到模拟的select上 $(select).bind("change click",function(){ $(selectFixDiv).text(setFixDivText($(this).val())); }); }; $.fn.selectFix=selectFix; })(jQuery);
Plug-in code running:
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(); }); } });
The following 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 major browsers.
But there is still a major flaw. In the old version of IE, the height of the real selection still cannot be expanded. Therefore, if the user clicks on the lower position of the simulated select, he will find that the select cannot be expanded! !
But the art of design is balance, and if you can't stand this flaw, you can use the first solution.
In addition, after testing, it was found that if the select is in a hidden container, then after displaying, the position of the select will be blank! !
What's going on? !
It turns out that the screen coordinates of an html element cannot be obtained after it is hidden! ! ! So when it is displayed, the real select is completely transparent, while the simulated select runs to the upper left corner of the screen. Because the coordinates of the select he obtained are (0,0)
Don’t worry, there are solutions to this problem:
1. Write code alone to trigger the beautification program of select
First, you need to make the following modifications to the beautification program running code above:
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" to the hidden select:
< select id = "sex" class = "selectInput" name = "sex" autoFix = "false" > < option value = "0" > 男 </ option > < option value = "1" > 女 </ option > </ select > <select id="sex" class="selectInput" name="sex" autoFix="false"> <option value="0">男</option> <option value="1">女</option> </select>
Then, when the external container is displayed, manually call $("#sex").selectFix()
2. If the display or hiding of the container is controlled by a third-party plug-in and it is inconvenient to modify it, you can consider the following solution:
In the beautification program, first determine whether the select is hidden. If not, the logic remains unchanged. If it is hidden, add a timer, loop to determine whether the element is displayed, automatically call fix when it is displayed, and then remove the timer
The code is as follows:
//加上隐藏select的操作 ( function ($){ var selectFix= function (){ var select=$( this ); //设置透明度为0 当然你也可以使用css控制 使用Jquery设置透明度可以屏蔽 透明度的 浏览器兼容性问题 $(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);
//加上隐藏select的操作 (function($){ var selectFix=function(){ var select=$(this); //设置透明度为0 当然你也可以使用css控制 使用Jquery设置透明度可以屏蔽 透明度的 浏览器兼容性问题 $(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 running code remains unchanged from the original one.