[英]How can I make a div stick to the top of the screen once it's been scrolled to?
我想創建一個 div,它位於內容塊的下方,但是一旦頁面滾動到足以接觸其頂部邊界,就會固定在適當的位置並隨頁面滾動。
您可以簡單地使用 css,將您的元素定位為fixed :
.fixedElement {
background-color: #c0c0c0;
position:fixed;
top:0;
width:100%;
z-index:100;
}
編輯:您應該擁有絕對位置的元素,一旦滾動偏移量到達該元素,則應將其更改為固定,並將頂部位置設置為零。
您可以使用scrollTop函數檢測文檔的頂部滾動偏移:
$(window).scroll(function(e){
var $el = $('.fixedElement');
var isPositionFixed = ($el.css('position') == 'fixed');
if ($(this).scrollTop() > 200 && !isPositionFixed){
$el.css({'position': 'fixed', 'top': '0px'});
}
if ($(this).scrollTop() < 200 && isPositionFixed){
$el.css({'position': 'static', 'top': '0px'});
}
});
當滾動偏移量達到 200 時,元素會粘在瀏覽器窗口的頂部,因為它是固定放置的。
您已經在 Google Code 的問題頁面和(最近才)在 Stack Overflow 的編輯頁面上看到了這個示例。
當您向上滾動時,CMS 的回答不會恢復定位。 這是從 Stack Overflow 無恥地竊取的代碼:
function moveScroller() {
var $anchor = $("#scroller-anchor");
var $scroller = $('#scroller');
var move = function() {
var st = $(window).scrollTop();
var ot = $anchor.offset().top;
if(st > ot) {
$scroller.css({
position: "fixed",
top: "0px"
});
} else {
$scroller.css({
position: "relative",
top: ""
});
}
};
$(window).scroll(move);
move();
}
<div id="sidebar" style="width:270px;">
<div id="scroller-anchor"></div>
<div id="scroller" style="margin-top:10px; width:270px">
Scroller Scroller Scroller
</div>
</div>
<script type="text/javascript">
$(function() {
moveScroller();
});
</script>
和一個簡單的現場演示。
一個新生的、無腳本的替代方法是position: sticky
,Chrome、Firefox 和 Safari 都支持它。 請參閱有關 HTML5Rocks和演示的文章以及Mozilla 文檔。
截至 2017 年 1 月和 Chrome 56 發布,大多數常用瀏覽器都支持 CSS 中的position: sticky
屬性。
#thing_to_stick {
position: sticky;
top: 0px;
}
在 Firefox 和 Chrome 中對我有用。
在 Safari 中,您仍然需要使用position: -webkit-sticky
。
Polyfill 可用於 Internet Explorer 和 Edge; https://github.com/wilddeer/stickyfill似乎是一個不錯的選擇。
我和你有同樣的問題,最終制作了一個 jQuery 插件來解決它。 它實際上解決了人們在此處列出的所有問題,此外它還添加了一些可選功能。
stickyPanelSettings = {
// Use this to set the top margin of the detached panel.
topPadding: 0,
// This class is applied when the panel detaches.
afterDetachCSSClass: "",
// When set to true the space where the panel was is kept open.
savePanelSpace: false,
// Event fires when panel is detached
// function(detachedPanel, panelSpacer){....}
onDetached: null,
// Event fires when panel is reattached
// function(detachedPanel){....}
onReAttached: null,
// Set this using any valid jquery selector to
// set the parent of the sticky panel.
// If set to null then the window object will be used.
parentSelector: null
};
https://github.com/donnyv/sticky-panel
演示: http : //htmlpreview.github.io/? https: //github.com/donnyv/sticky-panel/blob/master/jquery.stickyPanel/Main.htm
這是沒有jquery 的方法(更新:請參閱其他答案,您現在只能使用 CSS 執行此操作)
var startProductBarPos=-1; window.onscroll=function(){ var bar = document.getElementById('nav'); if(startProductBarPos<0)startProductBarPos=findPosY(bar); if(pageYOffset>startProductBarPos){ bar.style.position='fixed'; bar.style.top=0; }else{ bar.style.position='relative'; } }; function findPosY(obj) { var curtop = 0; if (typeof (obj.offsetParent) != 'undefined' && obj.offsetParent) { while (obj.offsetParent) { curtop += obj.offsetTop; obj = obj.offsetParent; } curtop += obj.offsetTop; } else if (obj.y) curtop += obj.y; return curtop; }
* {margin:0;padding:0;} .nav { border: 1px red dashed; background: #00ffff; text-align:center; padding: 21px 0; margin: 0 auto; z-index:10; width:100%; left:0; right:0; } .header { text-align:center; padding: 65px 0; border: 1px red dashed; } .content { padding: 500px 0; text-align:center; border: 1px red dashed; } .footer { padding: 100px 0; text-align:center; background: #777; border: 1px red dashed; }
<header class="header">This is a Header</header> <div id="nav" class="nav">Main Navigation</div> <div class="content">Hello World!</div> <footer class="footer">This is a Footer</footer>
這就是我用 jquery 做到的。 這些都是從堆棧溢出的各種答案拼湊而成的。 此解決方案緩存選擇器以提高性能,並且還解決了粘性 div 變得粘性時的“跳躍”問題。
在 jsfiddle 上查看: http : //jsfiddle.net/HQS8s/
CSS:
.stick {
position: fixed;
top: 0;
}
JS:
$(document).ready(function() {
// Cache selectors for faster performance.
var $window = $(window),
$mainMenuBar = $('#mainMenuBar'),
$mainMenuBarAnchor = $('#mainMenuBarAnchor');
// Run this on scroll events.
$window.scroll(function() {
var window_top = $window.scrollTop();
var div_top = $mainMenuBarAnchor.offset().top;
if (window_top > div_top) {
// Make the div sticky.
$mainMenuBar.addClass('stick');
$mainMenuBarAnchor.height($mainMenuBar.height());
}
else {
// Unstick the div.
$mainMenuBar.removeClass('stick');
$mainMenuBarAnchor.height(0);
}
});
});
這是另一種選擇:
爪哇腳本
var initTopPosition= $('#myElementToStick').offset().top;
$(window).scroll(function(){
if($(window).scrollTop() > initTopPosition)
$('#myElementToStick').css({'position':'fixed','top':'0px'});
else
$('#myElementToStick').css({'position':'absolute','top':initTopPosition+'px'});
});
您的#myElementToStick
應該以position:absolute
CSS 屬性開頭。
正如Josh Lee和Colin't Hart所說,您可以選擇只使用position: sticky; top: 0;
position: sticky; top: 0;
應用於您想要滾動的 div...
另外,您唯一需要做的就是將其復制到頁面頂部或將其格式化以適合外部 CSS 表:
<style>
#sticky_div's_name_here { position: sticky; top: 0; }
</style>
只需將#sticky_div's_name_here
替換為您的 div 的名稱,即如果您的 div 是<div id="example">
您將放置#example { position: sticky; top: 0; }
#example { position: sticky; top: 0; }
#example { position: sticky; top: 0; }
.
我的解決方案有點冗長,但它從左邊緣處理居中布局的可變定位。
// Ensurs that a element (usually a div) stays on the screen
// aElementToStick = The jQuery selector for the element to keep visible
global.makeSticky = function (aElementToStick) {
var $elementToStick = $(aElementToStick);
var top = $elementToStick.offset().top;
var origPosition = $elementToStick.css('position');
function positionFloater(a$Win) {
// Set the original position to allow the browser to adjust the horizontal position
$elementToStick.css('position', origPosition);
// Test how far down the page is scrolled
var scrollTop = a$Win.scrollTop();
// If the page is scrolled passed the top of the element make it stick to the top of the screen
if (top < scrollTop) {
// Get the horizontal position
var left = $elementToStick.offset().left;
// Set the positioning as fixed to hold it's position
$elementToStick.css('position', 'fixed');
// Reuse the horizontal positioning
$elementToStick.css('left', left);
// Hold the element at the top of the screen
$elementToStick.css('top', 0);
}
}
// Perform initial positioning
positionFloater($(window));
// Reposition when the window resizes
$(window).resize(function (e) {
positionFloater($(this));
});
// Reposition when the window scrolls
$(window).scroll(function (e) {
positionFloater($(this));
});
};
這里還有一個版本可以嘗試那些與其他版本有問題的人。 它將此重復問題中討論的技術結合在一起,並動態生成所需的輔助 DIV,因此不需要額外的 HTML。
CSS:
.sticky { position:fixed; top:0; }
查詢:
function make_sticky(id) {
var e = $(id);
var w = $(window);
$('<div/>').insertBefore(id);
$('<div/>').hide().css('height',e.outerHeight()).insertAfter(id);
var n = e.next();
var p = e.prev();
function sticky_relocate() {
var window_top = w.scrollTop();
var div_top = p.offset().top;
if (window_top > div_top) {
e.addClass('sticky');
n.show();
} else {
e.removeClass('sticky');
n.hide();
}
}
w.scroll(sticky_relocate);
sticky_relocate();
}
要使元素具有粘性,請執行以下操作:
make_sticky('#sticky-elem-id');
當元素變得粘性時,代碼會管理剩余內容的位置,以防止它跳入粘性元素留下的間隙。 當它向上滾動時,它還會將粘性元素返回到其原始的非粘性位置。
不是一個精確的解決方案,而是一個很好的替代方案
這個CSS ONLY 屏幕滾動條的頂部。 只用 CSS解決了所有問題,沒有JavaScript,沒有JQuery,沒有腦力工作(笑)。
享受我的小提琴:D 所有代碼都包含在那里 :)
CSS
#menu {
position: fixed;
height: 60px;
width: 100%;
top: 0;
left: 0;
border-top: 5px solid #a1cb2f;
background: #fff;
-moz-box-shadow: 0 2px 3px 0px rgba(0, 0, 0, 0.16);
-webkit-box-shadow: 0 2px 3px 0px rgba(0, 0, 0, 0.16);
box-shadow: 0 2px 3px 0px rgba(0, 0, 0, 0.16);
z-index: 999999;
}
.w {
width: 900px;
margin: 0 auto;
margin-bottom: 40px;
}<br type="_moz">
把內容足夠長的時間,所以你可以在這里看到效果:)呵呵,參考是有作為,因為他應該得到的事實, 他的功勞
這是 Josh Lee 答案的擴展版本。 如果您希望 div 位於右側的側邊欄上,並在一個范圍內浮動(即,您需要指定頂部和底部錨點位置)。 當您在移動設備上查看此內容時,它還修復了一個錯誤(您需要檢查左滾動位置,否則 div 將移出屏幕)。
function moveScroller() {
var move = function() {
var st = $(window).scrollTop();
var sl = $(window).scrollLeft();
var ot = $("#scroller-anchor-top").offset().top;
var ol = $("#scroller-anchor-top").offset().left;
var bt = $("#scroller-anchor-bottom").offset().top;
var s = $("#scroller");
if(st > ot) {
if (st < bt - 280) //280px is the approx. height for the sticky div
{
s.css({
position: "fixed",
top: "0px",
left: ol-sl
});
}
else
{
s.css({
position: "fixed",
top: bt-st-280,
left: ol-sl
});
}
} else {
s.css({
position: "relative",
top: "",
left: ""
});
}
};
$(window).scroll(move);
move();
}
我在搜索同樣的東西時遇到了這個。 我知道這是一個老問題,但我想我會提供一個更新的答案。
Scrollorama 有一個“固定”功能,這正是我想要的。
為回答另一個問題而提供的信息可能對您有所幫助,埃文:
您基本上想要修改元素的樣式以僅在驗證 document.body.scrollTop 值等於或大於元素的頂部后將其設置為固定。
我使用了上面的一些工作來創建這項技術。 我改進了一點,並認為我會分享我的工作。 希望這可以幫助。
function scrollErrorMessageToTop() {
var flash_error = jQuery('#flash_error');
var flash_position = flash_error.position();
function lockErrorMessageToTop() {
var place_holder = jQuery("#place_holder");
if (jQuery(this).scrollTop() > flash_position.top && flash_error.attr("position") != "fixed") {
flash_error.css({
'position': 'fixed',
'top': "0px",
"width": flash_error.width(),
"z-index": "1"
});
place_holder.css("display", "");
} else {
flash_error.css('position', '');
place_holder.css("display", "none");
}
}
if (flash_error.length > 0) {
lockErrorMessageToTop();
jQuery("#flash_error").after(jQuery("<div id='place_holder'>"));
var place_holder = jQuery("#place_holder");
place_holder.css({
"height": flash_error.height(),
"display": "none"
});
jQuery(window).scroll(function(e) {
lockErrorMessageToTop();
});
}
}
scrollErrorMessageToTop();
這是一種更動態的滾動方式。 它確實需要一些工作,我會在某個時候把它變成一個插件,但這是我工作一小時后想到的。
在 javascript 中,您可以執行以下操作:
var element = document.getElementById("myid");
element.style.position = "fixed";
element.style.top = "0%";
這是一個使用 jquery-visible 插件的示例: http : //jsfiddle.net/711p4em4/ 。
HTML:
<div class = "wrapper">
<header>Header</header>
<main>
<nav>Stick to top</nav>
Content
</main>
<footer>Footer</footer>
</div>
CSS:
* {
margin: 0;
padding: 0;
}
body {
background-color: #e2e2e2;
}
.wrapper > header,
.wrapper > footer {
font: 20px/2 Sans-Serif;
text-align: center;
background-color: #0040FF;
color: #fff;
}
.wrapper > main {
position: relative;
height: 500px;
background-color: #5e5e5e;
font: 20px/500px Sans-Serif;
color: #fff;
text-align: center;
padding-top: 40px;
}
.wrapper > main > nav {
position: absolute;
top: 0;
left: 0;
right: 0;
font: 20px/2 Sans-Serif;
color: #fff;
text-align: center;
background-color: #FFBF00;
}
.wrapper > main > nav.fixed {
position: fixed;
top: 0;
left: 0;
right: 0;
}
JS(包括 jquery-visible 插件):
(function($){
/**
* Copyright 2012, Digital Fusion
* Licensed under the MIT license.
* http://teamdf.com/jquery-plugins/license/
*
* @author Sam Sehnert
* @desc A small plugin that checks whether elements are within
* the user visible viewport of a web browser.
* only accounts for vertical position, not horizontal.
*/
var $w = $(window);
$.fn.visible = function(partial,hidden,direction){
if (this.length < 1)
return;
var $t = this.length > 1 ? this.eq(0) : this,
t = $t.get(0),
vpWidth = $w.width(),
vpHeight = $w.height(),
direction = (direction) ? direction : 'both',
clientSize = hidden === true ? t.offsetWidth * t.offsetHeight : true;
if (typeof t.getBoundingClientRect === 'function'){
// Use this native browser method, if available.
var rec = t.getBoundingClientRect(),
tViz = rec.top >= 0 && rec.top < vpHeight,
bViz = rec.bottom > 0 && rec.bottom <= vpHeight,
lViz = rec.left >= 0 && rec.left < vpWidth,
rViz = rec.right > 0 && rec.right <= vpWidth,
vVisible = partial ? tViz || bViz : tViz && bViz,
hVisible = partial ? lViz || rViz : lViz && rViz;
if(direction === 'both')
return clientSize && vVisible && hVisible;
else if(direction === 'vertical')
return clientSize && vVisible;
else if(direction === 'horizontal')
return clientSize && hVisible;
} else {
var viewTop = $w.scrollTop(),
viewBottom = viewTop + vpHeight,
viewLeft = $w.scrollLeft(),
viewRight = viewLeft + vpWidth,
offset = $t.offset(),
_top = offset.top,
_bottom = _top + $t.height(),
_left = offset.left,
_right = _left + $t.width(),
compareTop = partial === true ? _bottom : _top,
compareBottom = partial === true ? _top : _bottom,
compareLeft = partial === true ? _right : _left,
compareRight = partial === true ? _left : _right;
if(direction === 'both')
return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop)) && ((compareRight <= viewRight) && (compareLeft >= viewLeft));
else if(direction === 'vertical')
return !!clientSize && ((compareBottom <= viewBottom) && (compareTop >= viewTop));
else if(direction === 'horizontal')
return !!clientSize && ((compareRight <= viewRight) && (compareLeft >= viewLeft));
}
};
})(jQuery);
$(function() {
$(window).scroll(function() {
$(".wrapper > header").visible(true) ?
$(".wrapper > main > nav").removeClass("fixed") :
$(".wrapper > main > nav").addClass("fixed");
});
});
接受的答案有效,但如果您在其上方滾動,則不會移回之前的位置。 放在那里后總是粘在上面。
$(window).scroll(function(e) {
$el = $('.fixedElement');
if ($(this).scrollTop() > 42 && $el.css('position') != 'fixed') {
$('.fixedElement').css( 'position': 'fixed', 'top': '0px');
} else if ($(this).scrollTop() < 42 && $el.css('position') != 'relative') {
$('.fixedElement').css( 'relative': 'fixed', 'top': '42px');
//this was just my previous position/formating
}
});
jleedev 的回應可行,但我無法讓它發揮作用。 他的示例頁面也不起作用(對我來說)。
您可以添加 3 個額外的行,以便當用戶滾動回頂部時,div 將保留在其舊位置:
這是代碼:
if ($(this).scrollTop() < 200 && $el.css('position') == 'fixed'){
$('.fixedElement').css({'position': 'relative', 'top': '200px'});
}
我在 div 中設置了鏈接,因此它是字母和數字鏈接的垂直列表。
#links {
float:left;
font-size:9pt;
margin-left:0.5em;
margin-right:1em;
position:fixed;
text-align:center;
width:0.8em;
}
然后我設置了這個方便的 jQuery 函數來保存加載的位置,然后在滾動超出該位置時將位置更改為固定。
注意:這僅在頁面加載時鏈接可見時才有效!!
var listposition=false;
jQuery(function(){
try{
///// stick the list links to top of page when scrolling
listposition = jQuery('#links').css({'position': 'static', 'top': '0px'}).position();
console.log(listposition);
$(window).scroll(function(e){
$top = $(this).scrollTop();
$el = jQuery('#links');
//if(typeof(console)!='undefined'){
// console.log(listposition.top,$top);
//}
if ($top > listposition.top && $el.css('position') != 'fixed'){
$el.css({'position': 'fixed', 'top': '0px'});
}
else if ($top < listposition.top && $el.css('position') == 'fixed'){
$el.css({'position': 'static'});
}
});
} catch(e) {
alert('Please vendor admin@mydomain.com (Myvendor JavaScript Issue)');
}
});
最簡單的解決方案: demo
.container {
position: relative;
}
.sticky-div {
position: sticky;
top: 0;
}
<div class="container">
<h1>
relative container & sticky div
</h1>
<div class="sticky-div"> this row is sticky</div>
<div>
content
</div>
</div>
一直粘到頁腳碰到 div:
function stickyCostSummary() {
var stickySummary = $('.sticky-cost-summary');
var scrollCostSummaryDivPosition = $(window).scrollTop();
var footerHeight = $('#footer').height();
var documentHeight = $(document).height();
var costSummaryHeight = stickySummary.height();
var headerHeight = 83;
var footerMargin = 10;
var scrollHeight = 252;
var footerPosition = $('#footer').offset().top;
if (scrollCostSummaryDivPosition > scrollHeight && scrollCostSummaryDivPosition <= (documentHeight - footerHeight - costSummaryHeight - headerHeight - footerMargin)) {
stickySummary.removeAttr('style');
stickySummary.addClass('fixed');
} else if (scrollCostSummaryDivPosition > (documentHeight - footerHeight - costSummaryHeight - headerHeight - footerMargin)) {
stickySummary.removeClass('fixed');
stickySummary.css({
"position" : "absolute",
"top" : (documentHeight - footerHeight - costSummaryHeight - headerHeight - footerMargin - scrollHeight) + "px"
});
} else {
stickySummary.removeClass('fixed');
stickySummary.css({
"position" : "absolute",
"top" : "0"
});
}
}
$window.scroll(stickyCostSummary);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.