gpt4 book ai didi

javascript - 隐藏标题时将浏览器最大宽度(媒体查询)添加到javascript?

转载 作者:行者123 更新时间:2023-11-27 23:41:14 25 4
gpt4 key购买 nike

需要一些帮助*

我想控制我的隐藏标题 (javascript) 开始工作的宽度可以说:宽度为 667 像素及以下。它用于移动查看,但我不想使用:

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {

因为它不允许我控制一些更大的屏幕尺寸,比如大平板电脑/手机。

我看到了一些用于 javascript 的媒体查询脚本,但无法让它与您在下面看到的代码一起工作:

--> Fiddle

// 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;
}

最佳答案

如果您唯一的愿望是在视口(viewport)小于 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;
}
}

否则检查this answer我几天前给了。

我会重新发布代码,并附上一些可能对您有用的评论:

$(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();

这允许您控制所有媒体断点 - 只需在这两个断点旁边定义您的函数,并在适当的条件内调用它们。

关于javascript - 隐藏标题时将浏览器最大宽度(媒体查询)添加到javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31652373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com