footer当网页内容大于浏览器高度时跟随网页移动,当网页内容小于浏览器高度时固定在底部
<!DOCTYPE html>
<html>
<head>
<title>纯JS控制的智能Footer</title>
</head>
<body>
<div class="content">
<h1>网页内容</h1>
<p>这里是页面主要内容...</p>
</div>
<footer>版权所有 © 2023</footer>
<script>
(function() {
// 缓存DOM元素和样式
const body = document.body;
const footer = document.querySelector('footer');
const content = document.querySelector('.content');
// 初始化样式(完全用JS设置,不依赖CSS)
function initStyles() {
// 设置body基本样式
Object.assign(body.style, {
margin: '0',
padding: '0',
minHeight: '100vh',
position: 'relative' // 为fixed footer建立定位上下文
});
// 设置内容区域样式
if (content) {
Object.assign(content.style, {
paddingBottom: footer.offsetHeight + 'px' // 防止内容被fixed footer遮挡
});
}
// 设置footer基本样式
Object.assign(footer.style, {
backgroundColor: '#333',
color: 'white',
textAlign: 'center',
padding: '10px 0'
});
}
// 调整footer位置
function adjustFooter() {
const bodyHeight = Math.max(
body.scrollHeight,
body.offsetHeight,
body.clientHeight
);
if (bodyHeight <= window.innerHeight) {
Object.assign(footer.style, {
position: 'fixed',
bottom: '0',
left: '0',
right: '0'
});
} else {
footer.style.position = 'static';
}
}
// 初始化
initStyles();
adjustFooter();
// 监听事件
window.addEventListener('resize', adjustFooter);
// 更全面的MutationObserver配置
const observer = new MutationObserver(function(mutations) {
// 只有当DOM变化可能影响布局时才调用adjustFooter
for (let mutation of mutations) {
if (mutation.type === 'childList' ||
mutation.attributeName === 'style' ||
mutation.attributeName === 'class') {
adjustFooter();
break;
}
}
});
observer.observe(document.documentElement, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ['style', 'class']
});
// 确保在动态加载内容后也能正确调整
if (window.addEventListener) {
window.addEventListener('load', adjustFooter, false);
}
})();
</script>
</body>
</html>
免责声明: 本站数据均来自于互联网搜集,如有侵犯您的权利,请联系删除。→
获取金币← →
获取赞助码← →
帮助教程资源汇总←
根据我国《计算机软件保护条例》第十七条规定:“为了学习和研究软件内含的设计思想和原理,通过安装、显示、传输或者存储软件等方式使用软件的,可以不经软件著作权人许可,不向其支付报酬。”您需知晓本站所有内容资源均来源于网络,仅供用户交流学习与研究使用,版权归属原版权方所有,版权争议与本站无关,用户本人下载后不能用作商业或非法用途,需在24小时之内删除,否则后果均由用户承担责任。