浏览器窗口问题汇总

180 阅读1分钟

1. 浏览器窗口大小

1.1 获取屏幕尺寸

window.screen.width

1.2 获取可用工作区尺寸

window.screen.availWidth

1.3 获取body的宽高(不含边框)

document.body.clientWidth

1.4 获取网页的宽高

document.body.scrollWidth

1.5 获取body的宽高(含边框)

document.body.offsetWidth

1.6 获取元素到顶部的距离

document.querySelector('').offsetTop

1.7 获取滚动条到top和left的距离

document.body.scrollTop / document.documentElement.scrollTop

document.body.scrollLeft / document.documentElement.scrollLeft

2.滚动

2.1 滚动到指定位置
let h = document.querySelector('').offsetTop
// scrollTop滚动到指定位置
document.body.scrollTop = h
document.documentElement.scrollTop = h
// 解决ios兼容问题
window.scrollBy(0,h)
2.2 回到页面顶部

1、使用el-pagination实现翻页自动回到顶部

// main.js
Vue.prototype.$scrollTo = (x = 0, y = 0, type = 'smooth') => {
    window.scrollTo({
        top: x,
        left: y,
        behavior: type // 滚动行为:smooth平滑滚动,instant瞬间滚动,默认值auto,等同于instant
    })
}
// 使用方法
this.$scrollTo()

2、元素中绑定ref

<div ref="returnTop"></div>
this.$nextTick(() => {
    this.$refs.returnTop.scrollTop = 0
})

3、window.scrollTo()

window.scrollTo({
    top: 1000,
    behavior: "smooth" // 设置滚动行为改为平滑的滚动
})
  1. scrollIntoView() 滚动到指定元素上
document.querySelector(e).scrollIntoView({ behavior: "smooth", block: 'start' });
2.3 监听页面滚动
mounted () {
    window.addEventListener('scroll', this.scrollToTop)
},
scrollToTop() {
    var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
},

2.4 监听某元素滚动
<div ref="scrollContainer" @scroll="handleScroll" 
style="height: 300px; overflow-y: auto"></div> // 需要有滚动条才触发事件 
handleScroll (e) {
    if (e.srcElement.scrollTop + e.srcElement.clientHeight == e.srcElement.scrollHeight ) {
       console.log("嘿嘿我在底部触发了")
    }
},

2.5 监听窗口变化
mounted () {
    window.addEventListener('resize', this.getWindowSize)
},
getWindowSize() {
    console.log(window.innerWidth, window.innerHeight)
},

坑点

使用监听后,每次组件重新 mount 时都会添加一个新的事件监听器,导致事件响应函数会被执行多次。为了避免这种情况,可以在 beforeDestroy 钩子函数中移除事件监听器,这样如果组件被卸载,事件就不会被监听。

beforeDestroy() {
    // window.removeEventListener('resize', this.getWindowSize)
    window.removeEventListener(监听类型, 方法);
 },