HLJ 发布于
2025-06-11 13:54:52
0阅读

JavaScript窗口大小与滚动操作

JavaScript 中的 Window 大小和滚动

在 JavaScript 中,我们可以获取和操作浏览器窗口的大小以及滚动位置。以下是常用的属性和方法:

窗口大小

1. 窗口的宽度和高度

  • 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;

2. 屏幕尺寸

  • screen.width / screen.height - 整个屏幕的宽度/高度
  • screen.availWidth / screen.availHeight - 可用屏幕空间(减去任务栏等)

窗口滚动

1. 获取滚动位置

  • 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;

2. 滚动方法

  • 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);

响应窗口变化

1. 监听窗口大小变化

window.addEventListener('resize', function() {
  console.log('窗口大小已改变:', window.innerWidth, window.innerHeight);
});

2. 监听滚动事件

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));

实际应用示例

1. 检测用户是否滚动到底部

function isAtBottom() {
  return window.innerHeight + window.pageYOffset >= document.body.offsetHeight;
}

window.addEventListener('scroll', function() {
  if (isAtBottom()) {
    console.log('已滚动到底部');
    // 加载更多内容...
  }
});

2. 平滑滚动到顶部按钮

<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开发中非常有用,特别是在创建响应式设计、无限滚动、导航效果等交互功能时。

当前文章内容为原创转载请注明出处:http://www.good1230.com/detail/2025-06-11/856.html
最后生成于 2025-06-11 13:54:52
此内容有帮助 ?
0