我想在滚动到包含它的元素时自动播放我的猫头鹰传送带(v2)。由于某种原因,它会滑动一次,然后在我用鼠标进入时停止。
这是我要为其触发自动播放的html元素:
<div class="owl-carousel r-latest-news-list" id="r-latest-news-slider">
所有内容均已正确加载,因为如果我将自动播放设置为像通常那样在页面加载时开始,则可以正常工作。
这是我的代码,当在该元素上输入鼠标时触发自动播放:
if($("#r-latest-news-slider").length > 0){
var owl = $('#r-latest-news-slider').owlCarousel({
loop:true,
margin: 30,
items: 4,
nav: false,
dots: true,
responsive:{
0:{
items:2
},
600:
items:2
},
1000:{
items:4
}
}
})
$('#r-latest-news-slider').on("mouseenter", function(e) {
console.log('mouse enter');
owl.trigger('play.owl.autoplay', [2000]);
})
}
这是我正在关注的文档:https://owlcarousel2.github.io/OwlCarousel2/docs/api-events.html
答案 0 :(得分:0)
嘿,这里回答了这个问题:https://lazyfox.io/task/qP6/owl-carousel-autoplay-when-scrolling-to-element-not-working
if($("#r-latest-news-slider").length > 0) {
var owl = $('#r-latest-news-slider').owlCarousel({
loop: true,
margin: 30,
items: 4,
nav: false,
dots: true,
responsive: {
0: {
items:2
},
600: {
items:2
},
1000: {
items:4
}
}
});
}
// Function for checking if the element is in view
function isScrolledIntoView(elem) {
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
var animate = false;
// Function activated when scrolling
$(window).scroll(function() {
// Check if the element is visible
if(isScrolledIntoView("#r-latest-news-slider") && !animate) {
owl.trigger('play.owl.autoplay', [1000]);
animate = true;
console.log('Starting animation');
} else if(!isScrolledIntoView("#r-latest-news-slider") && animate) {
owl.trigger('stop.owl.autoplay', [1000]);
animate = false;
console.log('Stopping animation');
}
});