以下是我所做的:http://jsfiddle.net/cYHae/4/
以下是代码:
// <select> element displays its options on mousedown, not click.
showDropdown = function (element) {
var event;
event = document.createEvent('MouseEvents');
event.initMouseEvent('mousedown', true, true, window, 0, event.screenX, event.screenY, event.clientX, event.clientY,event.ctrlKey, event.altKey, event.shiftKey, event.metaKey, 0, null);
element.dispatchEvent(event);
};
// This isn't magic.
window.runThis = function () {
var dropdown = document.getElementById('dropdown');
showDropdown(dropdown);
};
它在Firefox中无效。为什么呢?
答案 0 :(得分:0)
很遗憾,您无法再强制打开 select
标签。我的建议是创建一个类似于 select
标签的元素。
这是一个例子(我在 full DEMO page 中看起来好多了):
$(document).ready(function() {
$('#ts').select2({
minimumResultsForSearch: -1,
width: 'resolve'
});
$("#click").click(function() {
$('#ts').select2('open');
});
});
.page-content{display:table-cell;vertical-align:middle}.wrapper{margin-left:auto;margin-right:auto;width:500px;background:#fff;background:linear-gradient(318deg,#e6f959 0,#16f3ff 100%);padding:3px;border-radius:16px;box-shadow:none;box-shadow:0 0 50px 15px rgba(0,0,0,.3)}.content{width:calc(100% - 16px);border-radius:13px;background:grey;background:rgba(0,0,0,.5);padding:8px}.select-container{display:inline-block;width:75%}.button-container{float:right;width:25%}.page{display:table;position:absolute;top:0;left:0;height:100%;width:100%}body{margin:0;padding:0;font-family:arial;height:100vh;width:100%;background:grey;background:radial-gradient(circle,#393939 0,#000 100%)}select{width:calc(100% - 8px)}button:focus{outline:0}button{font-size:12pt;width:100%;padding:6px;background:#000;color:#fff;background:rgba(0,0,0,.4);border-radius:6px;border:2px solid #000;border:2px solid rgba(0,0,0,.3);font-weight:700}.title{font-size:14pt;color:#fff;font-weight:700}.title-container{padding-bottom:4px}@media only screen and (max-width:550px){.wrapper{width:90%}}
<link href="https://app.jerc.me/test/js-open-select/style.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='page'>
<div class='page-content'>
<div class='wrapper'>
<div class='content'>
<div class='title-container'>
<span class='title'>Select a value</span>
</div>
<div class='select-container'>
<select id="ts">
<option value="1">1</option>
<option value="2">Lorem ipsum dolor s.</option>
<option value="3">3</option>
</select>
</div>
<div class='button-container'>
<button id="click">Open</button>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
我使用 select2.org 制作的。这是一个比您目前正在尝试做的更好的选择。抱歉迟到了 7 年?