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

问题描述

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



我尝试过:

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

但他们没有工作。



解决方案

我只是恢复这个老问题,因为我没有找到好的答案,我努力自己更好的方式来倾听滚动事件动态附加元件。



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



滚动事件在元素附加到DOM之后绑定,然后触发我自己的自定义事件。



(custom-scroll,.myDiv,function(){console.log(Scrolled:P);}上一篇下一篇暂无评论,我去发表〜评论(0) )$(#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;背景颜色:薰衣草overflow:auto; }  
 < script src =https:// ajax .googleapis.com / ajax / libs / jquery /2.1.0/jquery.min.js>< / script>< input type =buttonid =btnvalue =Click/& / code> 


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

I've tried:

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

But they didn't work.

DEMO

解决方案

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.

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.

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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 15:22