已封装为插件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 值呢?前端