为什么<选择多个>框在Chrome中使用preventDefault滚动到顶部 [英] Why do <select multiple> boxes scroll to the top with preventDefault in Chrome

查看:47
本文介绍了为什么<选择多个>框在Chrome中使用preventDefault滚动到顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每次我添加一个事件列表器,以某种方式对选择框进行 preventDefault 更改时,它都会滚动到顶部.

Every time I add an event listner that somehow does a preventDefault on a change to the select-box, it scrolls to the top.

有关一个最小的示例,请参见下文:

For a minimal example, see below:

document.getElementById('foo').onmousedown = function(e) {
  e.target.parentElement.focus();
  e.target.selected = !e.target.selected;
  e.preventDefault();
  return false;
}

<select multiple size="5" id="foo">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
</select>

重现此怪异行为的步骤是:

Steps to reproduce this weird behaviour is:

  1. 单击选项 2
  2. 向下滚动
  3. 单击任何选项元素

您的视图现在应该已经向上滚动,以使选项 2 位于最顶部.

Your view should now have scrolled up to have option 2 at the very top.

在我看来,这是一种奇怪的行为,真是令人讨厌.

This seems bizarre behaviour to me, which is really annoying.

有关此问题的后续问题:如何阻止这种情况的发生?我正在尝试制作一个脚本,该脚本使选择多个框的行为就像总是按下ctrl键一样(请参阅

Follow-up question to this: how can I stop this from happening? I'm trying to make a script that makes select multiple boxes behave as if the ctrl-key is always pressed (see https://stackoverflow.com/a/48217702/1256925) but that code doesn't work when the size is greater than the amount of options listed.

EDIT :我已经在MS Edge中对其进行了测试(我的PC上没有Firefox),而且似乎可以正确处理此问题,因此这可能是仅适用于Chrome的错误.如果是这样,我的后续问题仍然存在:如何防止Chrome执行此操作?(另外,有人可以告诉我这是否也发生在FF吗?)

EDIT: I've tested it in MS Edge (I don't have Firefox on this PC), and it seems to handle this correctly, so this might be a Chrome-only bug. If so, my follow-up question remains: how do I prevent Chrome from doing this? (Also, could someone update me on whether this happens in FF as well?)

推荐答案

尝试以下解决方法(至少在Chrome中有效):

Try this workaround (it works atleast in Chrome):

document.getElementById('foo').onmousedown = function(e) {
  e.preventDefault();
  var st = this.scrollTop;
  e.target.selected = !e.target.selected;
  setTimeout(() => this.scrollTop = st, 0);
  this.focus();
}

document.getElementById('foo').onmousemove= function(e) {
    e.preventDefault();
}

<select multiple size="5" id="foo">
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
<option>6</option>
<option>7</option>
<option>8</option>
<option>9</option>
<option>10</option>
</select>

这篇关于为什么&lt;选择多个&gt;框在Chrome中使用preventDefault滚动到顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆