的CSS刪除和添加保證金滾動
.menu {
margin-top: 100px;
width: 100%;
height: 25px;
position: fixed;
}
我努力做到最好的,當用戶向下滾動100像素從文檔的頂部,元素.menu
的margin-top
被刪除。
的CSS刪除和添加保證金滾動
.menu {
margin-top: 100px;
width: 100%;
height: 25px;
position: fixed;
}
我努力做到最好的,當用戶向下滾動100像素從文檔的頂部,元素.menu
的margin-top
被刪除。
在普通的JavaScript它可能看起來像這樣:
window.addEventListener('scroll', function() {
document.querySelector('.menu').style.marginTop =
Math.max(0, 100 - this.scrollY) + 'px';
}, false);
.menu {
margin-top: 100px;
width: 100%;
height: 25px;
position: fixed;
border: 1px dotted;
}
body {
height: 1000px;
margin: 0;
}
<div class="menu"></div>
好。當問這樣的問題時,你應該包括你已經嘗試過的解決方案。不只是要求我們讓你成爲代碼。但是...我感覺今天的慈善所以這裏是解決方案:
$(window).scroll(function(){
if($(window).scrollTop()>100){
$(".menu").css({"margin-top":"0"})
}else{
$(".menu").css({"margin-top":"100px"})
}
});
.menu {
margin-top: 100px;
width: 100%;
height: 25px;
position: fixed;
background:red;
transition:0.5s;
}
body {
height:500px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="menu">
</div>
雖然沒有提及jQuery,但是... – VisioN
沒有看到。但我確定他不介意JQ解決方案比純JS解決方案更清晰易懂 –
把你的代碼的HTML的jsfiddle –
把100px的保證金類如中'.menu.margin'。在滾動上使用javascript,eventlistener,當文檔從頂部大於100px時,移除類「.margin」。 –