gpt4 book ai didi

javascript - Slick.js - 响应式断点自定义函数

转载 作者:行者123 更新时间:2023-11-27 23:20:57 25 4
gpt4 key购买 nike

我正在尝试在 Slick.js 断点被触发时启动一个事件。
即使未命中断点,也会触发 init 事件。

有办法解决吗?

这是我的代码:

var $j = jQuery.noConflict();

$j(".homepage_slider").slick({
dots: false,
infinite: true,
arrows:false,
autoplay:true,
autoplaySpeed:3500,
slidesToShow: 1,
slidesToScroll: 1,
responsive: [
{
breakpoint: 480,
settings: {
init: changeImages()
}
}
]
});

function changeImages(){
$j('img.slider-image').each(function() {
$j(this).attr('src', $j(this).attr('data-mobile'));
});
}

我也试过了,但是没用:

$j('.homepage_slider').on('breakpoint', function(){
console.log("test");
$j('img.slider-image').each(function() {
$j(this).attr('src', $j(this).attr('data-mobile'));
});
});

有什么想法吗?

更新:

找到这个帖子:how to call different jquery actions in responsive design

var isBreakPoint = function (bp) {
var bps = [320, 480, 768, 1024],
w = $j(window).width(),
min, max
for (var i = 0, l = bps.length; i < l; i++) {
if (bps[i] === bp) {
min = bps[i-1] || 0
max = bps[i]
break
}
}
return w > min && w <= max
}

if (isBreakPoint(480)) {
$j('img.slider-image').each(function() {
$j(this).attr('src', $j(this).attr('data-mobile'));
});
}

此解决方法有效,但如果我找到一个在 Slick.js 断点事件被击中时有效的方法,那么两种方法之间没有差异,那就太好了。

最佳答案

查看 Slick's documentation 的“事件”部分:

In slick 1.4, callback methods have been deprecated and replaced with events.
<...>
breakpoint
Arguments: event, slick, breakpoint.
Fires after a breakpoint is hit.

所以你需要采取两个步骤:

  1. 使用 responsive 选项设置您需要的断点。
  2. 捕捉断点事件并做任何你想做的事情。

例如:

var $myCarousel = $('#myCarousel');

/* Step 1 */
$myCarousel.slick({
autoplay: true,
dots: true,
responsive: [
{ breakpoint: 500 },
{ breakpoint: 768 },
{ breakpoint: 992 }
]
});

/* Step 2 */
$myCarousel.on('breakpoint', function(event, slick, breakpoint) {
console.log('breakpoint ' + breakpoint);
});
/* Decorations */
.my-carousel img {
width: 100%;
}
.my-carousel .slick-next {
right: 15px;
}
.my-carousel .slick-prev {
left: 15px;
z-index: 1;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.7.1/slick.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.7.1/slick-theme.css">

<div id="myCarousel" class="my-carousel">
<div>
<img src="https://via.placeholder.com/900x300/c69/f9c/?text=1" alt="">
</div>
<div>
<img src="https://via.placeholder.com/900x300/9c6/cf9/?text=2" alt="">
</div>
<div>
<img src="https://via.placeholder.com/900x300/69c/9cf/?text=3" alt="">
</div>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.7.1/slick.min.js"></script>

关于javascript - Slick.js - 响应式断点自定义函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41131921/

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