option.style.display = “none” not working in safar

2019-01-12 09:26发布

This question already has an answer here:

This is the example I'm working on: http://jsfiddle.net/4suwY/5/

HTML:

<select id="asd">
    <option>hello</option>
    <option>I'M THE CHOSEN ONE</option>
    <option>asd</option>
    <option>wer</option>
    <option>qwe</option>
</select>

JS:

var sel = document.getElementById("asd");
var optnz = sel.getElementsByTagName("option")[1];
sel.value = optnz.value;
optnz.style.display = "none";

As you can see, it works in chrome, but it does not work in safari.. What it should do, is hide the "I'M THE CHOSEN ONE" option when you click the dropdown menu..

This is another test I made: http://jsfiddle.net/4suwY/11/

Same HTML, this is the JS:

var sel = document.getElementById("asd");
var opt = document.createElement("option");
opt.innerHTML = "YAYA";
opt.value = "YAYA";
sel.appendChild(opt);
sel.value = "YAYA";
opt.style.display = "none";

Anyway, what I need to do is display an option as selected (current), and hide to the user when the dropdown menu is opened, so he can't choose it.

Any suggestion / workaround? I don't see any error. What's wrong with Safari? Should I change approach? Jquery seems not to help.


EDITS:

I need to hide the options in the dropdownmenu, but at the same time I need to show this option "value" as the selected value! For example, the "closed" dropdown will show the value "I'M THE CHOSEN ONE", but if I click and open the menu, the only visible options will be "hello, asd, wer, qwe"..

1条回答
够拽才男人
2楼-- · 2019-01-12 09:55

You can't toggle display on <option> elements in Safari (or IE, for that matter). This is part of a long and inconsistent tradition with Safari restricting CSS styling functionality on form elements, believing the visual language of interactive elements should be consistent with the OS (no point trying to find a rationale for IE's failings).

Your only options are either to remove it (and re-append it later), or to set it to optnz.disabled = true. Sorry for the bad news!

查看更多
登录 后发表回答