使用jquery在页面加载完成的时候在页面的最顶端添加一个漂亮的div高度50px宽度填充整个页面里面显示当前时间如果页面有滚动条那么在滚动的时候该div是固定的不能使用绝对定位因为绝对定位会影响页面本身的内容
可以使用固定定位(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;
}
}
``
原文地址: https://www.cveoy.top/t/topic/fjiE 著作权归作者所有。请勿转载和采集!