在 iOS Safari 中模拟/触发选择框(可能带有触摸端)

Simulate/trigger select box in iOS Safari (perhaps with a touchend)

本文关键字:触摸 选择 Safari iOS 模拟      更新时间:2023-09-26

我有一个

<input type="button" id="sf" value="Select field"> 

<select id="rsf"><option value="something">Something</option><option... ... </select>

选择框与 visibility:hidden 一起隐藏,因此不可见。(它实际上是在按钮后面)

因此,当我单击该按钮时,我希望打开本机选择框,其中包含可供选择的不同可能性。可能性将是可见的,但选择框本身仍然是隐藏的。

它使用以下代码在桌面上工作:

$('#sf').on('touchend click', function() {
  var e = document.createEvent("MouseEvents");
  e.initMouseEvent("mousedown", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
  $('#rsf')[0].dispatchEvent(e);
});

我对document.createTouch和随之而来的所有内容(如e.initTouchEvent)都尝试了类似的方法......但没有任何运气....有人有解决方案吗?我想要这种方式的原因是因为我想在iOS中触发本机选择框UI。(或移动设备上的任何其他操作系统)。

我无法让它那样工作,所以我将选择框的不透明度设为 0,并将其放在按钮后面,并"pointer-events: none"按钮。 选择框的宽度和高度必须与按钮具有相同的尺寸,因此它还具有-webkit-appearance: none;appearance: none;还必须确保按钮的 z 索引高于选择框。

试试这个:如果你使用的是jquery。

  $('#sf').on('touchend click', function() {
        jQuery("#rsf").css({"visibility":"visible"});
        });

在普通的JavaScript中,你可以试试这个:

function myfunction(){
    document.getElementById("rsf").style.visibility='visible'
}

<input type="button" id="sf" value="Select field" onclick="myfunction()"> 

我设法通过element.focus()让它工作(在iOS 8,Cordova应用程序中测试)

所以:

$('select').on('touchend', function(ev) { ev.preventDefault(); ev.target.focus(); });