在 JavaScript 中,我们可以获取和操作浏览器窗口的大小以及滚动位置。以下是常用的属性和方法:
window.innerWidth / window.innerHeight - 包含滚动条的窗口内部宽度/高度window.outerWidth / window.outerHeight - 整个浏览器窗口的宽度/高度(包括工具栏等)document.documentElement.clientWidth / document.documentElement.clientHeight - 不包含滚动条的视口宽度/高度// 获取视口宽度
const viewportWidth = window.innerWidth || document.documentElement.clientWidth;
// 获取视口高度
const viewportHeight = window.innerHeight || document.documentElement.clientHeight;
screen.width / screen.height - 整个屏幕的宽度/高度screen.availWidth / screen.availHeight - 可用屏幕空间(减去任务栏等)window.pageXOffset / window.pageYOffset - 页面水平和垂直滚动距离(别名:scrollX / scrollY)document.documentElement.scrollLeft / document.documentElement.scrollTop - 类似功能// 获取当前滚动位置
const scrollX = window.pageXOffset || document.documentElement.scrollLeft;
const scrollY = window.pageYOffset || document.documentElement.scrollTop;
window.scrollTo(x, y) - 滚动到指定位置window.scrollBy(x, y) - 相对于当前位置滚动指定距离window.scroll() - 同 scrollTo()element.scrollIntoView() - 滚动使元素可见// 滚动到页面顶部
window.scrollTo(0, 0);
// 滚动到特定元素
document.getElementById('myElement').scrollIntoView({
behavior: 'smooth' // 平滑滚动
});
// 向下滚动100像素
window.scrollBy(0, 100);
window.addEventListener('resize', function() {
console.log('窗口大小已改变:', window.innerWidth, window.innerHeight);
});
window.addEventListener('scroll', function() {
console.log('当前滚动位置:', window.pageYOffset);
});
// 使用节流函数优化性能
function throttle(func, delay) {
let lastCall = 0;
return function() {
const now = new Date().getTime();
if (now - lastCall < delay) return;
lastCall = now;
func.apply(this, arguments);
};
}
window.addEventListener('scroll', throttle(function() {
console.log('节流滚动事件:', window.pageYOffset);
}, 100));
function isAtBottom() {
return window.innerHeight + window.pageYOffset >= document.body.offsetHeight;
}
window.addEventListener('scroll', function() {
if (isAtBottom()) {
console.log('已滚动到底部');
// 加载更多内容...
}
});
<button id="toTop" style="position: fixed; bottom: 20px; right: 20px; display: none;">↑</button>
<script>
const toTopBtn = document.getElementById('toTop');
window.addEventListener('scroll', function() {
toTopBtn.style.display = window.pageYOffset > 300 ? 'block' : 'none';
});
toTopBtn.addEventListener('click', function() {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
});
</script>
这些方法和属性在现代Web开发中非常有用,特别是在创建响应式设计、无限滚动、导航效果等交互功能时。
热门推荐:
0