Programming

프로그래밍 방식으로 HTML SELECT에 드롭 다운을 지시하는 방법 (예 : 마우스 오버로 인해)

procodes 2020. 8. 27. 22:29
반응형

프로그래밍 방식으로 HTML SELECT에 드롭 다운을 지시하는 방법 (예 : 마우스 오버로 인해)


프로그래밍 방식으로 HTML select에 드롭 다운을 지시 하는 방법 (예 : 마우스 오버로 인해)


HTML 선택 태그로는이 작업을 수행 할 수 없지만 JavaScript HTML로 수행 할 수 있습니다 . 이를 수행하는 기존의 다양한 컨트롤이 있습니다. 예를 들어 SO "관심 / 무시 태그"항목에 첨부 된 "제안"목록 또는 이메일 주소에 대한 Gmail 조회 등이 있습니다.

이 기능을 제공하는 JavaScript + HTML 컨트롤이 많이 있습니다. 아이디어에 대한 자동 완성 컨트롤을 찾으십시오.

자동 완성 컨트롤은이 링크를 참조하십시오 ... http://ajaxcontroltoolkit.codeplex.com/


이것은 HTML + Javascript로 가능하지만 다른 모든 사람들이 그렇지 않다고 말합니다.

그러나 이것은 Chrome에서만 작동합니다. 관심이 있으시면 더 읽어보십시오.


에 따르면 HTML5 절 3.2.5.1.7에 대한 W3C 작업 초안. 인터랙티브 콘텐츠 :

HTML의 특정 요소에는 활성화 동작이 있으므로 사용자가 활성화 할 수 있습니다. 이렇게 하면 키보드 나 음성 입력을 사용하거나 마우스 클릭을 통해 활성화 메커니즘 [...] 따라 일련의 이벤트가 트리거됩니다 .

사용자가 클릭하는 것 이외의 방식으로 정의 된 활성화 동작으로 요소를 트리거하는 경우 상호 작용 이벤트의 기본 동작은 요소에서 합성 클릭 활성화 단계 를 실행하는 것이어야합니다 .

<select>인터랙티브 콘텐츠이기 때문에 <option>s 를 프로그래밍 방식으로 표시 할 수 있다고 믿었습니다 . 몇 시간 동안 놀다가 사용 document.createEvent()하고 .dispatchEvent()작동 한다는 것을 발견했습니다 .

즉, 데모 시간입니다. 다음은 작동하는 Fiddle입니다.


HTML :

<select id="dropdown">
    <option value="Red">Red</option>
    <option value="Green">Green</option>
    <option value="Blue">Blue</option>
</select>
<br>
<button id="fire" type="button" onclick="runThis()">Show dropdown items</button>​

자바 스크립트 :

// <select> element displays its options on mousedown, not click.
showDropdown = function (element) {
    var event;
    event = document.createEvent('MouseEvents');
    event.initMouseEvent('mousedown', true, true, window);
    element.dispatchEvent(event);
};

// This isn't magic.
window.runThis = function () { 
    var dropdown = document.getElementById('dropdown');
    showDropdown(dropdown);
};

누구든지 Chrome이 아닌 동일한 작업을 수행하는 방법을 찾으면 이 바이올린을 자유롭게 수정하십시오 .


Xavier Ho의 답변은 현재 대부분의 브라우저에서 문제를 해결하는 방법을 다루고 있습니다. 그러나 더 이상 JavaScript로 이벤트를 '파견 / 수정하지 않는'것이 좋습니다 . ( mousedown이 경우 처럼 )

버전 53 이상부터 Google 크롬 은 신뢰할 수없는 이벤트에 대해 기본 작업을 수행하지 않습니다 . 스크립트에 의해 생성 또는 수정되거나 dispatchEvent메소드 를 통해 전달되는 이벤트와 같은 . 이 변경 사항은 이미 작업을 수행하지 않는 것으로 생각되는 Firefox 및 IE와 일치하기위한 것입니다.

테스트 목적으로 Fiddle 은 Xavier의 답변이 Chrome 53 이상에서 작동하지 않습니다. (나는 FF와 IE를 테스트하지 않습니다).

참조 링크 :

https://www.chromestatus.com/features/5718803933560832 https://www.chromestatus.com/features/6461137440735232

그리고 initMouseEvent도 더 이상 사용되지 않습니다.


이것은 내가 얻을 수있는 가장 가까운 것입니다. onmouseover 요소의 크기를 변경하고 onmouseout 크기를 복원합니다.

       <select onMouseOut="this.size=1;" onMouseOver="this.size=this.length;">
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
      </select>


i have this same problem and the easier way i found to solution this was with html and css.

select{
  opacity: 0;
  position: absolute;
}
<select>
  <option>option 1</option>
  <option>option 2</option>
  <option>option 3</option>
</select>
<button>click</button>


I think this is no longer possible in Chrome.

It seems version 53 of chrome disables this functionality as stated by Asim K T.

According to the spec http://www.w3.org/TR/DOM-Level-3-Events/#trusted-events

Trusted Events should not fire the default action (except click event).

They have however enabled it in webview, but I have not tested this.

We have found that some webviews are using fastclick inside them and due to a risk of breakage we are going to allow mousedown on selects even if they are untrusted.

And in this discussion the idea to let developers open a dropdown programatically is abandoned.


If any one is still looking for this :

<select id="dropdown">
    <option value="Red">Red</option>
    <option value="Green">Green</option>
    <option value="Blue">Blue</option>
</select>
<br>
<button id="fire" type="button" >Show dropdown items</button>

Javascript:

var is_visible=false; 

$(document).ready(function(){

    $('#fire').click(function (e) { 
    var element = document.getElementById('dropdown');


    if(is_visible){is_visible=false; return;}
    is_visible = true;

    var event;
    event = document.createEvent('MouseEvents');
    event.initMouseEvent('mousedown', true, true, window);
    element.dispatchEvent(event);

    /* can be added for i.e. compatiblity.
      optionsSelect.focus();
       var WshShell = new ActiveXObject("WScript.Shell");
       WshShell.SendKeys("%{DOWN}");
    */
    e.stopPropagation();
    return false;
});


$(document).click(function(){is_visible=false; });
});

Update:

One till there is no perfect solution to this problem, But you can try to avoid this scenario. Why do you want to do this. i was wondering for a solution few months back to make a select plugin for mobile devices

https://github.com/HemantNegi/jquery.sumoselect

Finally ended up with masking the custom div (or any other element) with a transparent select element, so that it can directly interacts with user.


Here's the best way I found. NOTE It only works with IE on Windows and your web would probably need to be in a secure zone - because we access the shell. The trick is that ALT-Down Arrow is a shortcut key to open a select drop down.

<button id="optionsButton" style="position:absolute;top:10px;left:10px;height:22px;width:100px;z-index:10" onclick="doClick()">OPTIONS</button>
<select id="optionsSelect" style="position:absolute;top:10px;left:10px;height:20px;width:100px;z-index:9">
    <option>ABC</option>
    <option>DEF</option>
    <option>GHI</option>
    <option>JKL</option>
</select>
<script type="text/javascript">
   function doClick() {
       optionsSelect.focus();
       var WshShell = new ActiveXObject("WScript.Shell");
       WshShell.SendKeys("%{DOWN}");
   }
</script>

Stop thinking that one thing is impossible, nothing is impossible to do, when you want to do.

Use this expand JS function created by a guy.

http://code.google.com/p/expandselect/

Include this JS and just call that passing the param as your select id, like that:

ExpandSelect(MySelect)

I may be wrong, but I don't believe that is possible with the default select box. You could do something with JS & CSS that achieves the desired result, but not (to my knowledge) the vanilla SELECT.


This is not exactly what you asked for, but I like this solution for its simplicity. In most cases where I am wanting to initiate a dropdown, it is because I'm validating that the user has actually made a selection. I change the size of the dropdown and focus it, which nicely highlights what they've skipped:

$('#cboSomething')[0].size = 3;
$('#cboSomething')[0].focus();

참고URL : https://stackoverflow.com/questions/249192/how-can-you-programmatically-tell-an-html-select-to-drop-down-for-example-due

반응형