javascript 手机上的视口单元

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 手机上的视口单元相关的知识,希望对你有一定的参考价值。

# Source: https://css-tricks.com/the-trick-to-viewport-units-on-mobile/

// First we get the viewport height and we multiple it by 1% to get a value for a vh unit)
const vh = window.innerHeight * 0.01
// Then we set the value in the --vh custom property to the root of the document
document.documentElement.style.setProperty('--vh', `${vh}px`)
/* To correct display height for mobile */
/* https://css-tricks.com/the-trick-to-viewport-units-on-mobile/ */
.header-background {
  height: 100vh;
  height: calc(var(--vh, 1vh) * 100);
  
  /* For mobile and landscape not use 100vh */
  @media screen and (orientation:landscape) {
    height: auto;
  }
  
  @media (min-width: $min-width-tablet) {
    height: auto;
  }
}


<script>
export default {
  data() {
    return {
      scrolled: false
    }
  },
  mounted: function () {
    // To correct display height for mobile
    if (process.browser) {
      window.addEventListener('scroll', this.handleScroll)
      this.displayCorrectHeightForMobile()
      window.addEventListener('resize', () => {
        this.displayCorrectHeightForMobile()
      })
    }
  },
  destroyed() {
    window.removeEventListener('scroll', this.handleScroll)
  },
  methods: {
    handleScroll() {
      this.scrolled = window.scrollY > 0
      const headerBackground = document.querySelector('.header-background')
      const offsetHeight = headerBackground.offsetHeight
      if (this.scrolled) {
        headerBackground.style.height = offsetHeight + 'px'
      }
    },
    displayCorrectHeightForMobile() {
      if (!this.scrolled) {
        // First we get the viewport height and we multiple it by 1% to get a value for a vh unit)
        const vh = window.innerHeight * 0.01
        // Then we set the value in the --vh custom property to the root of the document
        document.documentElement.style.setProperty('--vh', `${vh}px`)
      }
    }
  }
}
</script>

以上是关于javascript 手机上的视口单元的主要内容,如果未能解决你的问题,请参考以下文章

移动端web开发

使用 Pure Vanilla JavaScript 在视口上显示焦点 DIV 并在滚动时隐藏非焦点 DIV

ionic (webApp)软qv键盘打开时视口高度变小导致样式问题的解决方案

如何优雅地降级 CSS 视口单元?

视口单元在 Cordova 移动应用程序中不起作用

css CSS视口单元