Google Chrome浏览器自动滚动选择多个元素

时间:2020-06-04 23:42:23

标签: javascript jquery google-chrome

我正在开发一个jQuery插件,以在“选择多个”元素上显示复选框,但是我在谷歌浏览器中遇到问题。

由于某种原因,当我完成代码后,它会自动滚动到所选内容的顶部或底部。

我正在linux上使用chrome 83,并且已经在firefox 76上对其进行了测试,但是这种情况不会发生。

发生问题的gif可以在https://github.com/mmi9/i9multiselect/issues/1

中找到

这是代码的一部分:


        this.$select.prop('multiple', true).attr('multiple', 'multiple');
            this.$options = this.$select.children('option');
            let self = this;

            this.$select
                .mousedown((event) => { event.preventDefault(); })
                .mouseup((event) => { event.preventDefault(); })
                .focus((event) => {event.preventDefault(); })
                .click((event) => {
                    event.preventDefault();
                    self.$select.focus();
                    self.toggleOptionSelect($(event.target));
                })
                .keydown((event) => {
                    switch (event.code) {
                        case 'ArrowDown':
                            event.preventDefault();
                            self.focusNextPreviousOption();
                            break;
                        case 'ArrowUp':
                            event.preventDefault();
                            self.focusNextPreviousOption(true);
                            break;
                        case 'Space':
                            event.preventDefault();
                            self.toggleOptionSelect(self.$options.filter('[data-focus="true"]'));
                            break;
                    }
                });

            return this;

我尝试过event.preventDefault(),但是它不起作用。

这可能是Chrome错误吗?由于它可以在Firefox上运行。

回购位于https://github.com/mmi9/i9multiselect

编辑

可以在Selecting multiple from an html select element without using ctrl key

找到解决方案

我的解决方案:

        toggleOptionSelect($option) {
            const selectScrollTop = this.$select.scrollTop();

            if ($option.prop('selected') || $option.attr('selected') === 'selected') {
                $option.prop('selected', false).attr('selected', null);
            } else {
                $option.prop('selected', true).attr('selected', 'selected');
            }

            this.$options.filter('option[data-focus="true"]').data('focus', null).attr('data-focus', null).removeClass('focus');
            $option.data('focus', true).attr('data-focus', true).addClass('focus');

            setTimeout(() => { this.$select.scrollTop(selectScrollTop) }, 0);

            return this;
        };

0 个答案:

没有答案
相关问题