Scrollen: So korrigieren Sie Titel
P粉090087228
P粉090087228 2023-10-12 23:57:29
0
2
609

Ich erstelle einen Header, der fixiert wird und an Ort und Stelle bleibt, sobald er auf eine bestimmte Anzahl von Pixeln gescrollt wird.

Kann ich das nur mit CSS und HTML machen oder benötige ich auch JQuery?

Ich habe eine Demo erstellt, damit Sie es verstehen können. Jede Hilfe wäre großartig!

http://jsfiddle.net/gxRC9/4/

body{
     margin:0px;
     padding:0px;
}
 .clear{
     clear:both;
}
 .container{
     height:2000px;
}
 .cover-photo-container{
     width:700px;
     height: 348px;
     margin-bottom: 20px;
     background-color:red;
}
 .small-box{
     width:163px;
     height:100px;
     border:1px solid blue;
     float:left;
}
 .sticky-header{
     width:700px;
     height:50px;
     background:orange;
     postion:fixed;
}


P粉090087228
P粉090087228

Antworte allen(2)
P粉517090748

我修改了 Coop 的答案。请检查示例 FIDDLE 这是我的修改:

$(window).scroll(function(){
  if ($(window).scrollTop() >= 330) {
    $('.sticky-header').addClass('fixed');
   }
   else {
    $('.sticky-header').removeClass('fixed');
   }
});
P粉244155277

你需要一些 JS 来处理滚动事件。最好的方法是为固定位置设置一个新的 CSS 类,当滚动超过某个点时,该固定位置将分配给相关的 div。

HTML

<div class="sticky"></div>

CSS

.fixed {
    position: fixed;
    top:0; left:0;
    width: 100%; }

jQuery

$(window).scroll(function(){
  var sticky = $('.sticky'),
      scroll = $(window).scrollTop();

  if (scroll >= 100) sticky.addClass('fixed');
  else sticky.removeClass('fixed');
});

小提琴示例:http://jsfiddle.net/gxRC9/501/


编辑:扩展示例

如果触发点未知,但应该在粘性元素到达屏幕顶部时触发,则可以使用 offset().top

var stickyOffset = $('.sticky').offset().top;

$(window).scroll(function(){
  var sticky = $('.sticky'),
      scroll = $(window).scrollTop();

  if (scroll >= stickyOffset) sticky.addClass('fixed');
  else sticky.removeClass('fixed');
});

扩展示例小提琴:http://jsfiddle.net/gxRC9/502/

Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!