Step1
首先,先將HTML碼與CSS碼,放置網頁中,而這邊比較需要注意的地方,logo需準備二張,一黑一白同時div區塊的再加入data-color的屬性來標示出區塊的顏色,當白底為light,黑底為dark。
#html
<body class="df-light"> <div id="nav"> <a href="#" class="logo"> <img src="https://www.7-cha.com/images/logo-dark.png"> <img src="https://www.7-cha.com/images/logo.png"> </a>
</div> <div class="block div1" data-color="light"></div> <div class="block div2" data-color="dark"></div> <div class="block div3"></div>
body.df-light .logo>img:nth-of-type(2){ display: none; } body.df-light.mwt-dark .logo>img:nth-of-type(1){ display: none; } body.df-light.mwt-dark .logo>img:nth-of-type(2){ display: block; } #nav{ position: fixed; z-index: 999 } .div1{height:200px;} .div2{height:1000px; background: #111;} .div3{height: 1000px; background:#fff;}
Step2
這時當滾動畫面時,會發現當黑色底時,又遇到黑色LOGO時,就會有被吃掉的感覺。
Step3
這時再把jquery引用,並將下方的程式碼碼加入,並重整頁面後,再滾動一次,就會發現LOGO會隨著背景色而變換顏色啦!是不是超酷的呀!
$(function(){ $(window).scroll(function() { var $window = $(window), $body = $('body'), $block = $('.block'); var scroll = $window.scrollTop() + ($window.height() / 25); $block.each(function () { var $this = $(this);
if ($this.position().top <= scroll && $this.position().top + $this.height() > scroll) { $body.removeClass(function (index, css) { return (css.match (/(^|\s)mwt-\S+/g) || []).join(' '); }); if(typeof($(this).data('color')) !== 'undefined') { $body.addClass('mwt-' + $(this).data('color')); } } });
}).scroll(); });
#範例展示