[英]How can I make a div stick to the top of the screen once it's been scrolled to?
[英]How would I make div stick to top of screen using this code?
下面的代碼是我正在使用的測試代碼。 當藍色條到達頂部時,它應該會停留在屏幕頂部。
這適用於我的瀏覽器,但是我在這里的原因是,當它停留在頂部時,突然變小了。 如您所見,藍色條以整個容器的整個寬度開始,但是在我的計算機/瀏覽器上,藍色條停留在頂部之后,div縮小到僅文本大小。
更糟糕的是,我無法在jfiddle上重現該問題,因為在jfiddle中它根本無法工作! (圖像就在那里創建滾動條)。
這是jfiddle
這是jQuery:
var titlePosition = $('.title').offset().top;
$(window).scroll(function () {
var scrollBar = $(this).scrollTop();
if (scrollBar > titlePosition) {
$('.title').css("top", "0px");
$('.title').css("position", "fixed");
} else {
$('.title').css("position", "relative");
}
});
更新您的代碼:
if (scrollBar > titlePosition) {
$('.title').css("top", scrollBar+"px");
$('.title').css("position", "fixed");
} else {
$('.title').css("position", "static"); //otherwise it will still get that top value and cause unwanted position;
}
只需添加此CSS:
.title {
...
width: 100%; /*This does the trick*/
}
在這里,您可以使用它: http : //jsfiddle.net/edgarinvillegas/yPWAC/3/
干杯
也將left
設置為0
。 此外, 還有一些優化 。
我更喜歡追加/刪除類以將所有CSS放入樣式表中。 當代碼變得龐大時,您可以避免以后的問題(反正誰會在JS文件中尋找CSS?)。
另外,緩存對象。 每次觸發scroll
,您的代碼都會獲取DOM中的每個.title
並生成一個jQuery對象。 不是很理想。 取而代之的是,獲取所有.title
並在每個滾動條上進行修改。
CSS:
.title.fixed {
position:fixed;
left:0;
right:0;
top:0;
}
JS:
var titlePosition = $('.title').offset().top;
var win = $(window);
var title = $('.title');
win.scroll(function () {
var scrollBar = win.scrollTop();
if (scrollBar > titlePosition) title.addClass('fixed');
else title.removeClass('fixed');
});
至於不工作的小提琴,您忘了包括jQuery。 那應該在左上角找到。
嘗試給出z-index:999
或使用jQuery- $('.title').css("z-index", "999");
休息看起來還可以。
var titlePosition = $('.title').offset().top;
.top不是函數。 offset()返回一個包含top
和left
屬性的對象
用。。。來代替:
var titlePosition = $('.title').offset();
您現在可以像這樣訪問屬性:
titlePosition.top
或titlePosition.left
參考:.offset() http://api.jquery.com/offset/
感謝您的所有反饋。
盡管它有所改善,但最終div仍在調整大小。 將寬度固定為特定值的響應速度不夠。
我最終根據所有建議偶然發現了一個解決方案:
var titleWidth = $('.title').width()
/*then after the div is fixed I change the width */
$('.title').css("width",titleWidth);
我讓jquery保持div的原始寬度,然后將粘滯div的寬度更改為該值。
由於某些原因,即使我在CSS中定義了原始寬度,新的粘性寬度在瀏覽器中仍然會以不同的大小顯示。 因此,此方法將使其寬度與原始寬度相同(無論它是什么)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.