【问题标题】:Make it so that a script only works at a certain screen size使脚本仅适用于特定的屏幕尺寸
【发布时间】:2021-04-15 06:27:40
【问题描述】:
我正在使用页面构建器 Elementor 构建的 WordPress 页面正文中使用下面的代码 sn-p。我正在使用选项卡元素,我试图确保第一个选项卡在 768px 及以上打开但在 768px 及以下关闭。下面的脚本完美的关闭了tab元素,但是一直关闭,如何确保它只在768px及以下有效?
<script>
jQuery(document).ready(function($) {
var delay = 10; setTimeout(function() {
$('.elementor-tab-title').removeClass('elementor-active');
$('.elementor-tab-content').css('display', 'none'); }, delay);
});
</script>
【问题讨论】:
标签:
javascript
jquery
wordpress
tabs
elementor
【解决方案1】:
返回浏览器视口的宽度$( window ).width();
if ( jQuery(window).width() <= 768 ){
//do what ever
}
所以你会这样做:
jQuery(document).ready(function($) {
if ( jQuery(window).width() <= 768 ){
var delay = 10;
setTimeout(function() {
$('.elementor-tab-title').removeClass('elementor-active');
$('.elementor-tab-content').css('display', 'none');
}, delay);
}
});
【解决方案2】:
您可以计算视口宽度:
const vw = jQuery(window).width();
那么,
if(vw >= 768) {
var delay = 10; setTimeout(function() {
$('.elementor-tab-title').removeClass('elementor-active');
$('.elementor-tab-content').css('display', 'none'); }, delay);
});
}
【解决方案3】:
在 Elementor,您可以通过 body 的数据属性获取设备类型(“mobile”、“tablet”、“desktop”):
jQuery( 'body' ).data( 'elementor-device-mode' )