[英]Executing different jQuery on browser size (hover vs click)
在我的主導航中,我有一系列子菜單。 我的問題是,在常規瀏覽器尺寸上,我需要在懸停和移動視圖上打開菜單,我需要它在點擊時打開。 我有jQuery工作,但我不能關閉移動設備上的懸停和點擊常規視圖
HTML
<ul class="mainMenu">
<li>
ITEM
<ul class="subMenu">
<li></li>
</ul>
</li>
</ul>
jQuery (代碼可以工作,但無法關閉移動/常規視圖)
$(document).ready(function () {
$('.mainMenu li').hover(function () {
$(this).find('.subMenu').stop().fadeIn();
}, function () {
$(this).find('.subMenu').stop().fadeOut();
});
$('.mainMenu li').click(function () {
$(this).find('.subMenu').stop().slideToggle();
});
});
**還試過**(針對瀏覽器大小,代碼不再起作用)
var $browserWidth = window.innerWidth || document.documentElement.clientWidth;
if ($browserWidth > 768) {
$('.mainMenu li').hover(function () {
$(this).find('.subMenu').stop().fadeIn();
}, function () {
$(this).find('.subMenu').stop().fadeOut();
});
} else if($browserWidth < 768) {
$('.mainMenu li').click(function () {
$(this).find('.subMenu').stop().slideToggle();
});
}
看看這個鏈接 。
它詳細介紹了如何在JavaScript中使用媒體查詢。
基本上,有一個matchMedia()
函數,當你傳遞一個css媒體查詢時,其matches
屬性將返回一個布爾值。
所以在你的情況下:
if(window.matchMedia("(min-width: 768px)").matches){
//your desktop code
}
else{
//your mobile code.
}
@Ed Hinchcliffe讓我走上了正確的軌道......這就是最終完成工作的答案
$(document).ready(function () {
menuStuff();
});
$(window).resize(function () {
menuStuff();
});
function menuStuff() {
var $browserWidth = window.innerWidth || document.documentElement.clientWidth;
if ($browserWidth > 768) {
$('.mainMenu > li').unbind().bind({
mouseenter: function (e) {
$(this).find('.subMenu').stop().fadeIn();
},
mouseleave: function (e) {
$(this).find('.subMenu').stop().fadeOut();
}
})
} else {
$('.mainMenu > li').unbind().click(function () {
$(this).find('.subMenu').stop().slideToggle();
});
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.