我有以下JS / jQuery我已经设法构建,但它不是100%似乎与测试一起工作。主要是改变方向。我只想在iPad纵向和移动设备上点击要触发的事件。
这就是我所拥有的:
// mobile
var isMobile = window.matchMedia("only screen and (max-width : 40em)");
// tablet
var isTablet = window.matchMedia("only screen and (max-width : 60em)");
var isTabletPortraitOnly = window.matchMedia("only screen and (max-width : 60em) and (orientation : portrait)");
/* mobile cart slideout */
var $miniCart = $('#cart_over');
var $cartLink = $('.mini-cart');
var $siteContent = $('.top-header-container, .main-content, footer');
function cartOpen(){
event.preventDefault();
if ($miniCart.hasClass("cart-slide-in")) {
$miniCart.addClass("cart-slide-out");
$siteContent.addClass("content-slide-in");
} else if ($miniCart.hasClass("cart-slide-out")) {
$miniCart.removeClass('cart-slide-out');
$miniCart.addClass("cart-slide-in");
} else {
$miniCart.addClass("cart-slide-in");
}
if ($siteContent.hasClass("content-slide-out")) {
$siteContent.addClass("content-slide-in");
$siteContent.removeClass("content-slide-out");
} else if ($siteContent.hasClass("content-slide-in")) {
$siteContent.addClass("content-slide-out");
$siteContent.removeClass("content-slide-in");
} else {
$siteContent.addClass("content-slide-out");
}
}
function cartClose(){
//clode the lateral panel
if ($miniCart.hasClass("cart-slide-in")) {
$miniCart.removeClass('cart-slide-in');
$miniCart.addClass('cart-slide-out');
$siteContent.removeClass("content-slide-out");
$siteContent.addClass("content-slide-in");
event.preventDefault();
}
}
if(isMobile.matches || isTabletPortraitOnly.matches){
$cartLink.on('click', function(event){
cartOpen();
});
$('#cart_close').on('click', function(event){
cartClose();
});
}
//bind to resize
$(window).resize( function() {
if(isMobile.matches || isTabletPortraitOnly.matches){
$cartLink.on('click', function(event){
cartOpen();
});
$('#cart_close').on('click', function(event){
cartClose();
});
}
});
//check for the orientation event and bind accordingly
window.addEventListener("orientationchange", function() {
if(isMobile.matches || isTabletPortraitOnly.matches){
$cartLink.on('click', function(event){
cartOpen();
});
$('#cart_close').on('click', function(event){
cartClose();
});
}
}, false);
答案 0 :(得分:1)
当您的情况随时间变化时(移动旋转),您不应只检查一次。
将点击事件的if条件从外部更改为内部。
希望它有所帮助。