我有一個div
與position: absolute;
它在屏幕的右上角。在卷軸上隱藏絕對div
.selectState {
position: absolute;
top: 96px;
right: 0;
font-size: 12px;
background-color: #f1f1f1;
color: #428bca;
}
當用戶向下滾動時我想隱藏這個div
。如何用JavaScript或CSS做到這一點?
我有一個div
與position: absolute;
它在屏幕的右上角。在卷軸上隱藏絕對div
.selectState {
position: absolute;
top: 96px;
right: 0;
font-size: 12px;
background-color: #f1f1f1;
color: #428bca;
}
當用戶向下滾動時我想隱藏這個div
。如何用JavaScript或CSS做到這一點?
這裏是一個非jQuery的跨瀏覽器的解決方案:
window.addEventListener('scroll', function() {
var scrollAmount = window.scrollY || document.documentElement.scrollTop;
if (scrollAmount > 0)
document.querySelector('your-element').style.display = 'none';
else
document.querySelector('your-element').style.display = 'block';
});
這適用於IE8 +。 如果您希望div在用戶已經滾動一下時隱藏,只需將數字0更改爲您想要隱藏它的點。
如果你想使用jQuery,下面將做到這一點:
// detect when the window is being scrolled
$(window).scroll(function(){
// if the top is more than 96px (the top offset of your element)
if($(window).scrollTop() > 96){
// hide the element
$('.selectState').hide();
}else{
// otherwise show it
$('.selectState').show();
}
});
你可以進一步降低它:
$(window).scroll(function(){
$(window).scrollTop() > 96 ? $('.selectState').hide() : $('.selectState').show();
});
OP沒有要求jQuery,即使我犯了同樣的錯誤;) –
@ Mr.Alien - 因此是開頭的句子;)但是你說得對,從字面上來說它是一個JS請求 – SW4
爲此,您可以使用jQuery:
var $scrolldiv = $('#div'); // Add your div's id here
$(window).scroll(function() {
if ($(this).scrollTop() > 100) {
$scrolldiv.fadeIn();
} else if ($scrolldiv.is(':visible')) {
$scrolldiv.fadeOut();
}
});
你不能這樣做使用CSS。因爲CSS沒有方法來捕獲瀏覽器或窗口的事件。
但是,您可以使用JavaScript或jQuery來做到這一點。
$(window).scroll(function() { // scroll events
// hide it here using CSS or the show() hide() methods...
});
這樣,您可以獲取用戶在DOCUMENT中的位置並更改屬性。
我錯過了沒有添加到問題的jQuery,會刪除我的答案,費迪南德答案是一種方式去 –
這不是一個重複的問題,因爲另一個問題是處理JQuery。這裏沒有提到它。 –