已封裝爲插件javascript
scroll 事件性能優化問題。css
顯示所有
時,若是這條答案超出瀏覽器視窗,則收起
按鈕變成固定定位,js 計算出 right 值,bottom固定爲12px;當這條答案底部滾動至瀏覽器視窗內,收起
按鈕變回絕對定位。ps 發現知乎是否是改版了,以前答案底部出如今瀏覽器視窗內後這個位置是有收起按鈕的?,按鈕從固定定位變爲絕對定位並更改樣式,就像旁邊的做者保留權利
這樣的風格~(圖一直傳不上來。。暫時放棄了)<ul class="wrap"> <li> <div class="content all-content" style="display: none;"> <h2>Sheldon 座位理論</h2> <p>In the winter that seat is close enough to the radiator to remain warm and yet not so close as to cause perspiration. In the summer it's directly in the path of a cross breeze created by opening windows there, and there. It faces the television at an angle that is neither direct, thus discouraging conversation, nor so far wide to create a parallax distortion. I could go on, but ... I think I've made my point.</p> <p>冬季的時候,這個地方離電暖器很近、最暖和,可是又不會近到讓你感受熱、流汗; 夏天的時候,這裏又能夠吹由那兩扇窗戶吹進來的徐徐微風; 坐這的角度可讓我同時看電視又同時和他人聊天而不受影響, 剛好不會太遠也不會產生視覺上的錯覺。</p> <p>That is my spot. In an ever-changing world it is a simple point of consistency. If my life were expressed as a function in a four-dimensional Cartesian coordinate system, that spot, at the moment I first sat on it, would be 0000.</p> <p>那是個人專座。在這個不斷變化的世界裏,這是不變的一點。 假設個人生命用一個創建在四維直角座標系裏的方程來表示的話, 這個座位從我坐上那一刻開始就成爲了(0,0,0,0)。</p> </div> <div class="content part-content"> In the winter that seat is close enough to the radiator to remain warm and yet not so close as to cause perspiration. In the summer <b> ...</b> </div> <div class="sign unfold">展開</div> </li> </ul>
var doc = $(document); var win = $(window); // 屢次使用, 緩存起來 doc.on('click', '.unfold', function () { var unfold = $(this); if (unfold.text() !== '收起') { unfold.text('收起').siblings('.part-content').hide().siblings('.all-content').show(); var panel = unfold.parent(); var panelScroll = panel.offset().top + panel.height(); var scrollHeight = doc.scrollTop() + win.height(); var right = win.width() / 2 - 350 + 20 > 20 ? win.width() / 2 - 350 + 20 : 20; // 點擊展開按鈕時即判斷是否出現收起按鈕 if (scrollHeight - panelScroll < 50) { unfold.addClass('fold-fix').css('right', right); } // 綁定在 scroll 事件上 var cb = { onscroll: function() { var panelScroll = panel.offset().top + panel.height(); var scrollHeight = doc.scrollTop() + win.height(); var right = win.width() / 2 - 350 + 20 > 0 ? win.width() / 2 - 350 + 20 : 20; if (scrollHeight - panelScroll < 50 && panel.offset().top - scrollHeight < -90 && unfold.text() !== '展開') { unfold.addClass('fold-fix').css('right', right); } else { changeStyle(unfold); } win.off("scroll", cb.onscroll); setTimeout(function() { win.on("scroll", cb.onscroll); }, 50); } }; win.on("scroll", cb.onscroll); } else { var fold = $(this); changeStyle(fold); fold.text('展開').siblings('.part-content').show() .siblings('.all-content').hide(); } }); function changeStyle(i) { i.removeClass('fold-fix').css('right', '20px'); }
此處涉及一個知識點:網頁元素的絕對位置 && 相對位置html
如何動態設置固定定位的摺疊按鈕 的 right 值呢?前端