基于 window width-resize 启用和禁用脚本
Enable and disable script based on window width-resize
我想做的是当浏览器 window 宽度低于 1000px 例如,触发脚本 owl 轮播。但是当浏览器 window 宽度变得大于 1000px 时禁用 owl 轮播和内容再次正常显示。
当 window 超过 1000px 时我设法做到这一点并将其调整为低于 1000px 但是当我再次将其调整为超过 1000px 时它不会禁用 owl 轮播.
我的代码
<script type="text/javascript">
$(document).ready(function() {
$(window).resize(function() {
if ($(window).width() < 1000) {
$(".box").owlCarousel();
}
else {
//do nothing what to put here???
}
});
});
</script>
<div class="box">
<div class="product"></div>
<div class="product"></div>
<div class="product"></div>
<div class="product"></div>
<div class="product"></div>
<div class="product"></div>
<div class="product"></div>
<div class="product"></div>
</div>
如果 window 调整为 .box div,我也尝试使用 javascript 添加 class,但当 javascript它会在 1000 像素以下和以上调整大小,不会按照我的意愿动态更改。
能否告诉我实时检查浏览器宽度和 enable/disable owl 轮播的最佳方法?
Window.matchMedia()
可能是适合您的解决方案。来自文档:
Returns a new MediaQueryList object representing the parsed results of the specified media query string.
示例:
if (window.matchMedia("(max-width: 1000px)").matches) {
$(".box").owlCarousel();
} else {
/* however you disable the carousel... */
}
希望对您有所帮助!
我以前没有用过owlcarousel,但是快速查看the docs,我想你想使用owl.destroy()方法。
$(document).ready(function() {
$(".owl-carousel").owlCarousel()
//get carousel instance data and store it in variable owl
var owl = $(".owl-carousel").data('owlCarousel')
$(window).resize(function() {
if ($(window).width() < 1000) {
owl.reinit()
} else {
owl.destroy()
}
});
});
我想做的是当浏览器 window 宽度低于 1000px 例如,触发脚本 owl 轮播。但是当浏览器 window 宽度变得大于 1000px 时禁用 owl 轮播和内容再次正常显示。
当 window 超过 1000px 时我设法做到这一点并将其调整为低于 1000px 但是当我再次将其调整为超过 1000px 时它不会禁用 owl 轮播.
我的代码
<script type="text/javascript">
$(document).ready(function() {
$(window).resize(function() {
if ($(window).width() < 1000) {
$(".box").owlCarousel();
}
else {
//do nothing what to put here???
}
});
});
</script>
<div class="box">
<div class="product"></div>
<div class="product"></div>
<div class="product"></div>
<div class="product"></div>
<div class="product"></div>
<div class="product"></div>
<div class="product"></div>
<div class="product"></div>
</div>
如果 window 调整为 .box div,我也尝试使用 javascript 添加 class,但当 javascript它会在 1000 像素以下和以上调整大小,不会按照我的意愿动态更改。
能否告诉我实时检查浏览器宽度和 enable/disable owl 轮播的最佳方法?
Window.matchMedia()
可能是适合您的解决方案。来自文档:
Returns a new MediaQueryList object representing the parsed results of the specified media query string.
示例:
if (window.matchMedia("(max-width: 1000px)").matches) {
$(".box").owlCarousel();
} else {
/* however you disable the carousel... */
}
希望对您有所帮助!
我以前没有用过owlcarousel,但是快速查看the docs,我想你想使用owl.destroy()方法。
$(document).ready(function() {
$(".owl-carousel").owlCarousel()
//get carousel instance data and store it in variable owl
var owl = $(".owl-carousel").data('owlCarousel')
$(window).resize(function() {
if ($(window).width() < 1000) {
owl.reinit()
} else {
owl.destroy()
}
});
});