Selecting multiple from an html select element without using ctrl key

前端 未结 7 2253
灰色年华
灰色年华 2020-11-27 05:44

I\'ve come across various solutions to this issue on the net.

Basically, I find having to hold down ctrl a bit cheesy, and I want the select list to just select what

7条回答
  •  伪装坚强ぢ
    2020-11-27 06:21

    Here is a pure JS solution:

    element.onmousedown= function(event) {
        //this == event.target
        event.preventDefault();
        var scroll_offset= this.parentElement.scrollTop;
        this.selected= !this.selected;
        this.parentElement.scrollTop= scroll_offset;
    }
    element.onmousemove= function(event) {
        event.preventDefault();
    }
    

    Look at the parent element(the select box) and record the vertical scroll offset before selecting/deselecting the option. Then reset it manually once you have performed the action.

    The reasoning behind preventing default behavior for the mousemove event is because if you don't prevent it and you happen to click an option while moving the mouse, all options will become de-selected.

提交回复
热议问题