gpt4 book ai didi

jQuery 自定义滚动条和延迟加载

转载 作者:行者123 更新时间:2023-12-03 22:49:43 24 4
gpt4 key购买 nike

我有带有自定义内容滚动条的容器 jQuery custom content scroller :这段代码:

(function($){
$(window).load(function(){
$(".content").mCustomScrollbar({
scrollButtons: { enable: true },
mouseWheelPixels: 250
});
});
})(jQuery);

我想将它与延迟加载一起使用:

$(function() {
$("img.lazy").lazyload({
effect : "fadeIn",
container: $(".content")
});
});

我认为它应该与 Scroller 页面的回调函数一起使用,但我不擅长 jquery,所以我的结果不成功。

当我使用如下代码时,它会在页面加载时加载所有图像:

$(function() {
$("img.lazy").lazyload({
effect : "fadeIn",
container: $(".mCSB_container")
});
});

作者说这可以通过编写一个简单的js函数并在 whileScrolling 上调用它来完成事件。

感谢您的帮助。

最佳答案

您尝试使用container不起作用,因为mCustomScrollbar不使用滚动容器,而是使用overflow:hidden容器中的相对定位来实现滚动。我能想到的最干净的方法是使用自定义[触发延迟加载的事件][1]。以下是我对 Hasan Gürsoy 给出的示例文件的做法:

<script>
$(document).ready(function () {
var filledHeight = 250;
$(window).load(function () {
$(".scroll").height($(window).height() - filledHeight);
$(".scroll").mCustomScrollbar({ scrollButtons: { enable: true },
mouseWheelPixels: 250,
callbacks: { whileScrolling: function() {
var scroller = $(".mCSB_container");
var scrollerBox = scroller.closest(".mCustomScrollBox");
$(".scroll img.lazy").filter(function() {
var $this = $(this);
if($this.attr("src") == $this.data("src")) return false;
var scrollerTop = scroller.position().top;
var scrollerHeight = scrollerBox.height();
var offset = $this.closest("div").position();
return (offset.top < scrollerHeight - scrollerTop);
}).trigger("lazyScroll");
}}});

$("img.lazy").lazyload({ event: "lazyScroll" });
});
});
</script>

我还使用了 whileScrolling 回调,但只是为了检查哪些 img.lazy 图像可见。如果它们与容器的相对位置不大于容器的高度减去其 CSS top 属性,则它们是。 (假设您总是从上→下滚动;此设置无法识别由于您向下滚动太远而不可见的图像。)对于这些图像,该函数然后会触发自定义 lazyScroll 事件,该事件是延迟加载用于触发加载图像。

请注意,此解决方案还不太可移植:您必须将 .mCSB_container.mCustomScrollBox 的查询替换为获取关联元素的查询使脚本能够在具有多个 mCustomScrollbar 的情况下使用当前滚动框。在现实场景中,我还会缓存 jQuery 对象,而不是在每次调用回调时重新创建它们。

关于jQuery 自定义滚动条和延迟加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15532362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com