可能需要一些帮助*
我想控制我的隐藏头(javascript)开始工作的宽度,让我们说:在宽度667px和向下。这是为移动观看,但我不想使用:
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
因为它不能让我控制一些更大的屏幕,比如大的平板电脑/手机。
我看到了一些javascript的媒体查询脚本,但是不能让它与下面的代码一起工作:
——>小提琴
// Hide header on scroll down //
var didScroll;
var lastScrollTop = 0;
var delta = 44;
var navbarHeight = $('header').outerHeight();
$(window).scroll(function(event){
didScroll = true;
});
setInterval(function() {
if (didScroll) {
hasScrolled();
didScroll = false;
}
}, 250);
function hasScrolled() {
var st = $(this).scrollTop();
// Make sure they scroll more than delta
if(Math.abs(lastScrollTop - st) <= delta)
return;
// If they scrolled down and are past the navbar, add class .nav-up.
// This is necessary so you never see what is "behind" the navbar.
if (st > lastScrollTop && st > navbarHeight){
// Scroll Down
$('header').addClass('nav-up');
} else {
// Scroll Up
if(st + $(window).height() < $(document).height()) {
$('header').removeClass('nav-up');
}
}
lastScrollTop = st;
}
如果你唯一的愿望是隐藏你的头(你的问题是不完全清楚),当视口小于n像素时,你不需要任何js。使用简单的css媒体查询:
@media screen and (max-width: 667px) {
.your-header-class {
display: none;
}
}
但是如果你想先使用手机,你应该这样做:
/* general + mobile css */
.your-header-class {
display: none;
}
/* tablet + desktop css only */
@media screen and (min-width: 667px) {
.your-header-class {
display: block;
}
}
否则,看看我几天前给出的答案。
我将重新发布这些代码,并附上一些可能对你有用的注释:
$(window).resize(function() {
// This will make sure your 'media query' will only run,
// once your viewport has stopped changing in size
clearTimeout(resizeTimer);
resizeTimer = setTimeout(breakpointChange(), 400);
});
function breakpointChange() {
// your window width
width = window.innerWidth;
// adapt the values (i.e. 667) here
if (!mobile && width < 667) {
tablet = desktop = false;
mobile = true;
// this is mobile, so execute your js here
}
if (!tablet && width > 401 && width < 768) {
mobile = desktop = false;
tablet = true;
console.log('is tablet');
}
if (!desktop && width > 769) {
mobile = tablet = false;
desktop = true;
console.log('is desktop');
}
}
// you'll need to call $(window).resize(); the first time your script loads
$(window).resize();
这允许您控制所有媒体断点—只需在这两个断点旁边定义函数,并在适当的条件中调用它们。