[英]How to make fixed navbar transparent based on page scroll?
我希望mynavbar在頁面滾動到頂部時是透明的,但是當用戶滾動時,我希望它變得不透明。 我使用javascript進行了嘗試,但是仍然無法正常工作。 http://jsfiddle.net/6A6qy/
function myFunction() { if ($(window).scrollTop() < 50) { document.getElementById("masthead").style.opacity = "0.5"; } }
#masthead { position: fixed; top: 0; left: 0; z-index: 9999; width: 100%; height: 50px; background-color: #00a087; opacity: 1; } #container { background-color: blue; height: 1000px; display: block; margin-top: -50px; }
<body onload="myFunction()"> <nav id="masthead"> <!-- Fixed navigation bar content --> </nav> <div id="container"></div> </body>
這個怎么樣:
JS:
// listen for scroll
$(window).scroll( function() {
// apply css classes based on the situation
if ($(".masthead").offset().top > 100) {
$(".masthead").addClass("navbar-scrolled");
} else {
$(".masthead").removeClass("navbar-scrolled");
}
}
CSS:
.navbar-scrolled {
/* some css for navbar when scrolled */
}
JSFiddle示例: http : //jsfiddle.net/8ruwnaam/
然后,當然,您可以添加一些優化措施,以確保在類已經存在的情況下不會一直應用它們。 但是如果沒有這樣的東西,它也可以正常工作。
其他事項:
此答案的第一個版本和您的問題使用ID進行樣式設置,對於許多人來說,這並不是一個好主意。 樣式ID違背DRY原則,當您忘記考慮CSS特異性時,會引起所有這些有趣的小問題。 當涉及到JS中的邏輯之類的東西時,ID對於很多事情來說都還不錯,但是請嘗試使用類進行樣式設計。
您應該創建一個.opaque
css類,並根據活動滾動或scrollTop
<50來附加它:
.opaque {
opacity: 0.5;
}
然后將該類附加到on('scroll')
或scrollTop
(使用debounce插件 )上:
function myFunction() {
var $masthead = $('#masthead')
, $window = $(window);
// currently scrolling
$window.scroll($.debounce( 250, true, function(){
$masthead.addClass('opaque');
}));
// done scrolling
$window.scroll($.debounce( 250, function(){
// if at the top, add or keep opaque class
if($(this).scrollTop() < 50) {
if(!$masthead.hasClass('opaque')) {
$masthead.addClass('opaque');
}
} else {
$masthead.removeClass('opaque');
}
}));
}
您需要將其默認設置為透明(因為它將在頂部),像這樣
#masthead {
position: fixed;
top: 0;
left: 0;
z-index: 9999;
width: 100%;
height: 50px;
background-color: #00a087;
opacity: 0.5; /*edited the opacity to be 50% by default*/
}
然后使用此腳本來滿足您的需求:
$(document).ready(function () {
$(window).scroll(function(){
var ScrollTop = parseInt($(window).scrollTop());
if (ScrollTop < 100) {
document.getElementById("masthead").style.opacity = "0.5";
} else {
document.getElementById("masthead").style.opacity = "1";
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.