可以使用固定定位(position: fixed)来实现该需求。以下是对应的代码:

HTML 部分:

<body>
  <!-- 页面内容 -->
  
  <div class='top-bar'>
    <div class='time-wrapper'>
      <span class='time'></span>
    </div>
  </div>
  
  <!-- 其他内容 -->
</body>

CSS 部分:

.top-bar {
  height: 50px;
  width: 100%;
  background-color: #333;
  color: #fff;
  text-align: center;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9999;
}

.time-wrapper {
  line-height: 50px;
}

.time {
  font-size: 20px;
}

JavaScript 部分:

$(document).ready(function() {
  // 在页面顶部添加固定的top-bar
  $('body').prepend('<div class="top-bar"><div class="time-wrapper"><span class="time"></span></div></div>');

  // 滚动时top-bar固定不动
  $(window).scroll(function() {
    $('.top-bar').css('top', $(this).scrollTop() + 'px');
  });

  // 更新时间
  updateTime();
  setInterval(updateTime, 1000);
});

function updateTime() {
  var now = new Date();
  var hours = now.getHours();
  var minutes = now.getMinutes();
  var seconds = now.getSeconds();
  $('.time').text(addZero(hours) + ':' + addZero(minutes) + ':' + addZero(seconds));
}

function addZero(num) {
  if (num < 10) {
    return '0' + num;
  } else {
    return num;
  }
}
jQuery 实现页面顶部固定时间显示条 - 无绝对定位

原文地址: https://www.cveoy.top/t/topic/oaON 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录