使用 Javascript/jQuery 打开选择?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2048213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Open Select using Javascript/jQuery?
提问by Newbie
Is there a way to open a select box using Javascript (and jQuery)?
有没有办法使用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>
I have to open my select, cause of ie bug. All versions of IE (6,7,8) cut my options. As far as I know, there is no css bugfix for this. At the moment I try to do the following:
我必须打开我的选择,即错误的原因。所有版本的 IE (6,7,8) 都削减了我的选择。据我所知,没有针对此的 css 错误修复。目前我尝试执行以下操作:
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;
});
}
But clicking on my select the first time will change the width of the select but I have to click again to open it.
但是第一次点击我的选择会改变选择的宽度,但我必须再次点击才能打开它。
采纳答案by Newbie
Okay, I found another way fixing this problem. Here is the fix:
好的,我找到了解决此问题的另一种方法。这是修复:
Please give me feedback! I'm kind of proud on myself ;)
请给我反馈!我有点为自己感到骄傲;)
$(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();
}
回答by Newbie
Instead of using click, you could use the mousedownhandler to capture the mousedownevent.
mousedownfires before click, so you could call stopPropogationto break the event queue.
click您可以使用mousedown处理程序来捕获mousedown事件,而不是使用。
mousedown之前触发click,因此您可以调用stopPropogation中断事件队列。
回答by Matt H
I know this is pretty old and answered, but this worked for me in Safari and iOS UIWebView - I have it hidden, but want it to show and open when a different button is clicked.
我知道这很旧并且得到了回答,但这在 Safari 和 iOS UIWebView 中对我有用 - 我隐藏了它,但希望它在单击不同的按钮时显示和打开。
$('#select-id').show().focus().click();
回答by joseantgv
Try this:
尝试这个:
dropDown = function (elementId) {
var dropdown = document.getElementById(elementId);
try {
showDropdown(dropdown);
} catch(e) {
}
return false;
};
showDropdown = function (element) {
var event;
event = document.createEvent('MouseEvents');
event.initMouseEvent('mousedown', true, true, window);
element.dispatchEvent(event);
};
Then call the function:
然后调用函数:
dropDown('elementId');
回答by uesports135
Try this:
尝试这个:
var myDropDown=$("#myDropDown");
var length = $('#myDropDown> option').length;
//open dropdown
myDropDown.attr('size',length);
and this to close:
这要关闭:
//close dropdown
myDropDown.attr('size',0);
回答by Harijs Krūtainis
回答by Brendan Kowitz
First of all, I feel the pain of this limitation in IE - bleh! Just thought I'd also share this as it seems to be working for me. I've taken almost the same approach, but on a per select element. In my case I know which lists could have long data.
首先,我感受到了 IE 中这种限制的痛苦 - bleh!只是想我也会分享这个,因为它似乎对我有用。我采取了几乎相同的方法,但在每个选择元素上。就我而言,我知道哪些列表可能有很长的数据。
Instead of making the select elements absolute, I've kept them inline and wrap them in a DIV with a hidden overflow as appearance needed to be consistent, also it only applies this 'hack' if it is IE and the expanded width is greater than the current width.
我没有使选择元素成为绝对的,而是将它们保持内联并将它们包装在一个带有隐藏溢出的 DIV 中,因为外观需要保持一致,如果它是 IE 并且扩展宽度大于当前宽度。
To use this for all select boxes you could use something like:
要将其用于所有选择框,您可以使用以下内容:
$("select").each(function(){
$(this).IELongDropDown();
});
Or obviously on a per element bases by id. Here's the jquery plugin:
或者显然基于 id 的每个元素。这是jquery插件:
(function($) {
$.fn.IELongDropDown = function(cln) {
if (jQuery.browser.msie) { //only IE has problems with long select boxes
var el = this;
var previousWidth = el.width();
var divWrapper = "<div style='padding:0;margin:0;overflow:hidden;width:"+ previousWidth +"px'></div>";
el.wrap(divWrapper);
var newWidth = el.width("auto").width();
el.width(previousWidth);
if(newWidth > previousWidth) {
el.bind("mousedown", function(){ return el.width("auto").focus(); });
el.bind("blur", function(){ return el.width(previousWidth); });
el.bind("change", function(){ return el.width(previousWidth); });
}
}
return this;
};
})(jQuery);
Hope this helps someone
希望这有助于某人
回答by Yoni
I think that you need to return true from your event handlers (click, blur, etc.) so after your handler executes, the browser continues to propagate the event and open the select.
我认为您需要从您的事件处理程序(单击、模糊等)返回 true,以便在您的处理程序执行后,浏览器继续传播事件并打开选择。
It is similar with href links, if they have an onclick handler and the handler returns false, the link is not followed (the browser stops the event after your handler executes).
它与 href 链接类似,如果它们有一个 onclick 处理程序并且处理程序返回 false,则不会跟踪该链接(浏览器在您的处理程序执行后停止该事件)。
EDIT:Based on your comment and answer, it seems that your handler gets the first chance to execute only after the browser decides to open the box.
I suggest that you try the focusevent handler, it might get a chance to run earlier than the clickhandler and perhaps before the browser actually opens the box. It is also more consistent (applies both to mouse and keyboard navigation).
编辑:根据您的评论和回答,您的处理程序似乎只有在浏览器决定打开框后才第一次有机会执行。
我建议您尝试使用focus事件处理程序,它可能比click处理程序更早运行,并且可能在浏览器实际打开框之前运行。它也更加一致(适用于鼠标和键盘导航)。
回答by Mark Schultheiss
I prefer to set my CSS in a CSS file and then "addClass" but even so, your code (portion)
我更喜欢在 CSS 文件中设置我的 CSS,然后“addClass”但即便如此,您的代码(部分)
$('select').blur(function(){
$(this).css({
'position' : 'relative',
'width' : original_width
});
});
$('select').blur(function(){
$(this).css({
'position' : 'relative',
'width' : original_width
});
});
seems to be a duplicate
似乎是重复的
I would make it:
我会做到:
$('select').blur().css({
'position' : 'relative',
'width' : original_width
});
Not sure you really even need the .blur() here what with the .change() event (try taking it out see see if that addresses your issue...I use select often on IE and do not seem to have an issue.
不确定您是否真的需要 .blur() 此处的 .change() 事件(尝试将其取出,看看是否可以解决您的问题...我经常在 IE 上使用 select 并且似乎没有问题。
回答by Jni
The mousedown event is raise before the click event :
mousedown 事件在 click 事件之前引发:
- first mousedown raise -> set the width to 'auto' (if the state of the dropdown is 'close')
- click raise -> store in a var the state of the dropdown : 'open'
- We select a value, the second mousedown is raised : nothing to do
- click raise -> we need to restore the original width of the dropdown and change the state of the var to : 'close'
- 首先 mousedown raise -> 将宽度设置为“自动”(如果下拉菜单的状态为“关闭”)
- 单击 raise -> 将下拉列表的状态存储在 var 中:“打开”
- 我们选择一个值,第二次mousedown被抬起:无事可做
- 单击 raise -> 我们需要恢复下拉列表的原始宽度并将 var 的状态更改为:'close'
The blur and change event are needed to close the dropdown if the user clicked outside the dropdown.
如果用户在下拉列表外单击,则需要使用 blur 和 change 事件来关闭下拉列表。
Here the complete solution with Brendan's code :
这里是布伦丹代码的完整解决方案:
(function ($) {
var open = {}
$.fn.IELongDropDown = function (cln) {
if (jQuery.browser.msie) { //only IE has problems with long select boxes
var el = this;
var id = el.attr('id');
var margin = 2; //Need to set a margin however the arrow is cut
var previousWidth = el.width() + margin;
var divWrapper = "<div style='padding:0;margin:0;overflow:hidden;width:" + previousWidth + "px'></div>";
el.wrap(divWrapper);
var newWidth = el.width("auto").width();
el.width(previousWidth);
if (newWidth > previousWidth) {
el.mousedown(function () {
if (!open[id]) {
el.width("auto");
el.focus();
}
});
el.click(function () {
if (!open[id])
open[id] = true;
else {
open[id] = false;
return el.width(previousWidth);
}
});
el.blur(function () {
open[id] = false;
return el.width(previousWidth);
});
el.change(function () {
open[id] = false;
return el.width(previousWidth);
});
}
}
return this;
};
})(jQuery);
Call the function :
调用函数:
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$('#mydropdownlist').IELongDropDown();
});
</script>

