[英]How to capture scroll event on Select2 dropdown?
How to capture the scroll
event for HTML element that using Select2
? 如何使用Select2
捕获HTML元素的scroll
事件? I want to capture the scroll event for dynamically adding <option>
into my dropdown. 我想捕获滚动事件以将<option>
动态添加到下拉菜单中。
For your infomation: 为您的信息:
jQuery
, and the dropdown using Select2
. 我使用的是jQuery
,下拉菜单使用的是Select2
。 id
that of my HTML element is d
. 我的HTML元素的id
是d
。 (Although the naming isn't appropriate, will rename it later) (尽管命名不合适,稍后会重命名) Testing solution 1: (Not working) 测试解决方案1 :(不起作用)
$("body").on("scroll", "#select2-d-results", function(){
alert('scroll');
})
Testing solution 2: (Not working) 测试解决方案2 :(无效)
$('#select2-d-results').scroll(function() {
alert('scroll');
});
The problem is due to the scroll event does not bubble up in DOM 问题是由于滚动事件未在DOM中冒泡
Method 1 方法1
Using mousewheel
event instead of scroll 使用mousewheel
事件代替滚动
Method 2 (recommended) 方法2 (推荐)
Using addEventListener
使用addEventListener
Jquery .on('scroll') not firing the event while scrolling jQuery .on('scroll')在滚动时不触发事件
$("#d").select2(); // using on mousedown $("body").on("mousewheel", "#select2-d-results", function(){ console.log('mousewheel'); }) // using addEventListener document.addEventListener('scroll', function (event) { if (event.target.id === 'select2-d-results') { console.log('scrolling'); } }, true);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://rawgit.com/select2/select2/master/dist/js/select2.js"></script> <link href="https://rawgit.com/select2/select2/master/dist/css/select2.min.css" rel="stylesheet" /> <select id="d" style="width: 300px"> <option value="1">Argentina</option> <option value="2">Brazil</option> <option value="3">China</option> <option value="4">India</option> <option value="5">Indonesia</option> <option value="1">Argentina</option> <option value="2">Brazil</option> <option value="3">China</option> <option value="4">India</option> <option value="5">Indonesia</option> </select>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.