将滚动事件绑定到动态 DIV? [英] Bind scroll Event To Dynamic DIV?

查看:24
本文介绍了将滚动事件绑定到动态 DIV?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,在使用 AJAX 之后,我将拥有一个可滚动的 DIV.如何将滚动事件绑定到它?

For example, after using AJAX, I'll have a scrollable DIV. How to bind scroll events to it?

我试过了:

$(window).on("scroll", ".mydiv", function(){...})
$(document).on("scroll", ".mydiv", function(){...})
$(".mydiv").on("scroll", function(){...})
$(".mydiv").scroll(function(){...})

但它们没有用.

演示

推荐答案

我只是在重温这个老问题,因为我没有找到好的答案,我一直在努力寻找更好的方式来监听动态附加元素的滚动"事件.

I am just reviving this old question because I didn't find good answer and I struggled myself for better way to listen 'scroll' event for dynamically appended element.

由于 Scroll 事件不会在 DOM 中冒泡,因此我们不能像用于滚动那样使用 on().所以我想出了侦听我自己的自定义触发事件 在我想要侦听滚动"事件的元素中.

Since Scroll event does not bubble up in the DOM due to this we can't use on() like we use for scroll. So I came up with listening my own custom triggered event in the element where I would want to listen the 'scroll' event.

scroll 事件是在元素被追加到 DOM 之后然后触发我自己的自定义事件之后绑定的.

The scroll event is binded after the element is appended on the DOM followed by triggering my own custom event.

$("body").on("custom-scroll", ".myDiv", function(){
    console.log("Scrolled :P");
})

$("#btn").on("click", function(){
    $("body").append('<div class="myDiv"><br><br><p>Content1<p><br><br><p>Content2<p><br><br></div>');
    listenForScrollEvent($(".myDiv"));
});


function listenForScrollEvent(el){
    el.on("scroll", function(){
        el.trigger("custom-scroll");
    })
}

body{ font-family: tahoma; font-size: 12px; }
	
	.myDiv{
		height: 90px;
		width: 300px;
		border: 1px solid;
		background-color: lavender;
		overflow: auto;
	}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="button" id="btn" value="Click"/>

这篇关于将滚动事件绑定到动态 DIV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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