แก้ปัญหาความกว้าง option ของ select tag ใน ie ด้วย jQuery และ css อย่างง่าย

ความกว้างของ option ใน ie กรณีเรากำหนดค่าความกว้าง ให้กับ tag select เช่น

<select name="myselect" id="myselect" style="width:150px;">

และข้อความในรายการ option มีขนาดกว้างกว่า ค่าที่กำหนด จะทำให้ข้อความในรายการ option
แสดงไม่หมด ซึ่งต่างจาก browser ตัวอื่นๆ ที่ปัญหานี้จะไม่เกิดขึ้น

กรณีปัญหา เมื่อเปิดผ่าน IE

กรณีบราวเซอร์อื่น

แก้ปัญหาโดยวิธีการต่อไปนี้

CSS code

<style type="text/css">
div.hideSelect{
	position:relative;
	width:150px; /* กำหนดค่าให้เท่ากับความกว้างเริ่มต้นที่ต้องการ */
	height:22px;
	overflow:hidden;
}
div.hideSelect select{
	position:absolute;
	float:left;
}
</style>

HTML code

<div class="hideSelect">
<select name="myselect" id="myselect" style="width:150px;" >
<option value="ใช้ PHP สร้าง Javascript อย่างง่าย ">ใช้ PHP สร้าง Javascript อย่างง่าย </option>
<option value="PHP MySQL connecting script and function ">PHP MySQL connecting script and function </option>
<option value="ตรวจสอบสถานะของ MySQL ด้วย phpinfo ">ตรวจสอบสถานะของ MySQL ด้วย phpinfo </option>
<option value="การสร้างวันเวลาปัจจุบัน ด้วยฟังก์ชัน date() ">การสร้างวันเวลาปัจจุบัน ด้วยฟังก์ชัน date() </option>
</select>  
</div> 

Javascript Code

<script src="http://www.google.com/jsapi" type="text/javascript"></script>  
<script type="text/javascript">  
google.load("jquery", "1.3.2");  
</script>  
<script type="text/javascript">  
$(function(){ 
    var mybrowser=navigator.userAgent;   
    if(mybrowser.indexOf('MSIE')>0){   
		$("div.hideSelect select").hover(function(){
				$(this).width("auto");
		},function(event){
				 if(event.relatedTarget!=null){
					$(this).width(150); // กำหนดค่าให้เท่ากับความกว้างเริ่มต้นที่ต้องการ
				 }
				$("div.hideSelect select").bind("change blur",function(){
					$(this).width(150); // กำหนดค่าให้เท่ากับความกว้างเริ่มต้นที่ต้องการ
				});
		});
    }   	
});  
</script>

ตัวอย่าง



หรือคลิกดูตัวอย่างต่อไปนี้ใน IE http://www.ninenik.com/demo/fix_select.php

บทความในหมวดที่่น่าสนใจ อื่นๆ jQuery Learning

07 Dec 09 การเลื่อน scrollbar อัตโนมัติตาม การเลื่อนขึ้นลง ของ mouse ด้วย jQuery อ่าน 450 02 Feb 10 หมุน สลับ แบนเนอร์ในแนวนอน ด้วย jQuery อย่างง่าย อ่าน 433 27 Jan 10 การใช้งาน jQuery.contains() ใน jQuery 1.4 อ่าน 325 01 Feb 10 การใช้งาน method delay() ใน jQuery 1.4 อ่าน 301 26 Jan 10 การใช้งาน method .clearQueue() ใน jQuery 1.4 javascript library เวอร์ชั่นล่าสุด อ่าน 275 24 Feb 10 เทคนิค สร้าง effect add to cart ด้วย jQuery อย่างง่าย อ่าน 275 19 Feb 10 สร้าง Horizontal Accordion แนวนอน ด้วย jQuery อย่างง่าย อ่าน 257
จำนวนผู้เยี่ยมชม 84567 คน 2010 © Copyright ninenik.com. All rights reserved.