我想通過使用jQuery在用戶距頂端不同距離時刪除/添加類。使用jQuery在頁面上的不同高度添加和刪除類
我已經成功地完成了它,它工作正常,但我認爲我做錯了,我希望你的幫助來優化代碼。
html很簡單,基本上這些部分(包括標題)具有100%的寬度。和不同的顏色。我想在第一部分(爲了美學目的)改變標題的顏色。 而且我還希望它在頁面滾動超過1個像素時有陰影。
我正在通過添加/刪除類來做到這一點。
當我使用一個大的if語句時,它不能很好地工作,因爲每當任何條件匹配時,js就停止檢查其他匹配項,所以它不適用所有需要的類。
接下來的代碼有效,但正如我所說的,我認爲這不是最佳/不好的寫法。 下面是HTML標記:
<header class="dark no-shadow">
Header
</header>
<section class="blue">
Please Scroll Down to see the header changes...
</section>
<section>
The header color Should change when you pass through me.
</section>
這裏是jQuery代碼:(!像我)
var header = $('header'),
blueSection = $('section.blue'),
// Calculate when to change the color.
offset = blueSection.offset().top + blueSection.height() - header.height();
$(window).scroll(function(){
var scroll = $(window).scrollTop();
// Remove Class "dark" after scrolling over the dark section
if (scroll >= offset) {
header.removeClass('dark');
} else {
header.addClass('dark');
}
// Remove Class "no-shadows" whenever not on the top of the page.
if (scroll >= 1) {
header.removeClass('no-shadow');
} else {
header.addClass('no-shadow');
}
});
而對於那些你們誰喜歡用的jsfiddle: https://jsfiddle.net/shock/wztdt077/6/
感謝前面的傢伙!
在這裏查看如何在您滾動某處後執行操作 - http://stackoverflow.com/questions/25660289/show-hide-div-when-passed-the-other-div/25661103#25661103 - 您可以通過div的位置或像素 – Tasos
演示使用以上的代碼 - https://jsfiddle.net/tgaoyx4b/ – Tasos
這可能應該去http://codereview.stackexchange.com/ – xpy