New*_*bie 27 javascript jquery javascript-events
有没有办法使用Javascript(和jQuery)打开一个选择框?
<select style="width:150px;">
<option value="1">1</option>
<option value="2">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc arcu nunc, rhoncus ac dignissim at, rhoncus ac tellus.</option>
<option value="3">3</option>
</select>
Run Code Online (Sandbox Code Playgroud)
我必须打开我的选择,因为bug.所有版本的IE(6,7,8)都削减了我的选择.据我所知,这没有css bugfix.目前我尝试执行以下操作:
var original_width = 0;
var selected_val = false;
if (jQuery.browser.msie) {
$('select').click(function(){
if (selected_val == false){
if(original_width == 0)
original_width = $(this).width();
$(this).css({
'position' : 'absolute',
'width' : 'auto'
});
}else{
$(this).css({
'position' : 'relative',
'width' : original_width
});
selected_val = false;
}
});
$('select').blur(function(){
$(this).css({
'position' : 'relative',
'width' : original_width
});
});
$('select').blur(function(){
$(this).css({
'position' : 'relative',
'width' : original_width
});
});
$('select').change(function(){
$(this).css({
'position' : 'relative',
'width' : original_width
});
});
$('select option').click(function(){
$(this).css({
'position' : 'relative',
'width' : original_width
});
selected_val = true;
});
}
Run Code Online (Sandbox Code Playgroud)
但是第一次点击我的选择将改变选择的宽度,但我必须再次点击打开它.
尝试这个:
var myDropDown=$("#myDropDown");
var length = $('#myDropDown> option').length;
//open dropdown
myDropDown.attr('size',length);
Run Code Online (Sandbox Code Playgroud)
并关闭:
//close dropdown
myDropDown.attr('size',0);
Run Code Online (Sandbox Code Playgroud)
我知道这已经很老了并且已经回答了,但这在Safari和iOS UIWebView中对我有用 - 我把它隐藏起来,但是想要在点击不同的按钮时显示和打开它.
$('#select-id').show().focus().click();
Run Code Online (Sandbox Code Playgroud)
好吧,我找到了另一种方法来解决这个问题。这是修复方法:
请给我反馈!我为自己感到骄傲;)
$(document).ready(function() {
if (jQuery.browser.msie) {
select_init();
}
});
function select_init () {
var selects = $('select');
for (var i = 0; i < selects.length; i++) {
_resizeselect.init(selects[i]);
}
}
var _resizeselect = {
obj : new Array(),
init : function (el) {
this.obj[el] = new resizeselect (el);
}
}
function resizeselect (el) {
this.el = el;
this.p = el.parentNode;
this.ht = el.parentNode.offsetHeight;
var obj = this;
this.set = false;
el.onmousedown = function () {
obj.set_select("mousedown");
}
el.onblur = function () {
obj.reset_select("blur");
}
el.onchange = function () {
obj.reset_select("change");
}
}
resizeselect.prototype.set_select = function (str) {
if (this.set) {
this.set = false;
return;
}
this.el.style.width = "auto";
this.el.style.position = "absolute";
this.p.style.height = this.ht + "px";
this.p.style.zIndex = 100;
this.set = true;
this.el.focus();
}
resizeselect.prototype.reset_select = function (str) {
this.el.style.width = "";
this.el.style.position = "";
this.p.style.height = "";
this.p.style.zIndex = 1;
this.set = false;
window.focus();
}
Run Code Online (Sandbox Code Playgroud)