我正在学习JavaScript。我创建了一个带有两个div的导航栏:
并添加了一个函数,以便当用户向下滚动时,第一个div将为fadeOut:
$(document).ready(function() {
var $nav = $('.first-nav'); //Caching element
// fade in .navbar
$(function() {
$(window).scroll(function() {
// set distance user needs to scroll before we start fadeIn
if ($(this).scrollTop() > 275) {
$nav.fadeOut("fast");
} else {
$nav.fadeIn();
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav class="navbar navbar-default navbar-fixed-top pages">
<div class="container-fluid first-nav">
<button id="nav-toggle" data-target=".sidebar-right" data-toggle="sidebar" class="navbar-toggle toggle-right" type="button">
<span></span>
</button>
<a href="" id="login-button">Login</a>
<a href="/#get_quote"><button id="get_quote_navbar" name="get_quote_navbar" class="btn btn-login">Get Quote</button></a>
<a href="tel:8774000232" class="phone-number-link"><i class="fa fa-phone"></i> (877) 400-0232</a>
<!-- Logo -->
<a href="/" class="navbar-brand" id="brand-desktop"></a>
<!-- /Logo -->
<a href="" id="nav-desktop">Home</a>
<a href="" id="nav-desktop">For Home</a>
<a href="" id="nav-desktop">For Bussiness</a>
</div>
<div id="navigation" class="col-md-12 sub-nav">
<div class="col-md-6 sub-nav-left">
<a href="" id="sub-left">Commercial</a>
<a href="" id="sub-left">Construction</a>
<a href="" id="sub-left">Multy-family</a>
<a href="" id="sub-left">Partnership</a>
</div>
<div class="col-md-3 sub-nav-right">
<a href="/#get_quote"><button id="get_quote" name="get_quote_navbar" class="btn btn-quote">Get Quote</button></a>
</div>
</div>
</nav>
一切正常。在CSS中,我为最小和最大宽度创建了@media。当我这样做时,桌面和平板电脑都很好,但是当我想把固定的第一个div用于移动时,JavaScript会出现问题而且我在向上滚动时眨了眼。
如何添加JS函数if (width < 1024) then $nav.fadeIn();
?
答案 0 :(得分:1)
尝试:
if ($(window).width() < 1024) {
$nav.fadeIn();
}
答案 1 :(得分:0)
如果您想在javaScript中使用媒体查询,只需使用window.matchMedia()
,如下所示:
if (window.matchMedia("(min-width: 400px)").matches) {
/* the viewport is at least 400 pixels wide */
} else {
/* the viewport is less than 400 pixels wide */
}
完整参考:https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia
要获得调整窗口大小的效果,您需要执行以下操作:
function foo(){
//code here
}
foo();
$(window).on('resize orientationchange',foo);
答案 2 :(得分:0)
谢谢你们,我成功了。这是一个代码。
$(document).ready(function(){
var $nav = $('.first-nav');//Caching element
// hide .navbar first - you can also do this in css .nav{display:none;}
// fade in .navbar
$(function () {
$(window).scroll(function () {
if ($(this).scrollTop() > 275 && $(window).width() > 1024) {
$nav.fadeOut("fast");
} else {
$nav.fadeIn();
}
});
});
});
答案 3 :(得分:-1)
你可以这样做以测试窗口,
注意:更改窗口大小时必须刷新页面
var widthScreen = window.matchMedia('(max-width: 1023px)').matches;
if(widthScreen){
$nav.fadeIn();
}