吸頂效果—position:sticky的vue組件化和兼容性解決


封裝

<template> <div class="header_sticky"> <slot></slot> </div> </template> <script> export default { name: 'stickyHeader', computed: { randomId: function(){ return 'randomId_' + Number(Math.random().toString().substr(3,3) + Date.now()).toString(36); }, targetElement_: function() { return this.$el } },
  mounted() {
   //獲取高度變化
    this.$refs.sticky_.sticky() 
  }, methods: { // css: 用於替換的css樣式; (一般用默認的) sticky_(css='sticky_') { if (CSS.supports('position', 'sticky') || CSS.supports('position', '-webkit-sticky')) { console.log('>>>>>>>>> sticky is supported') } else { let newNodeTop; let header = this.targetElement_; if(document.getElementById(this.randomId)) { newNodeTop = document.getElementById(this.randomId); }else{ newNodeTop = document.createElement("div"); newNodeTop.id = this.randomId; header.parentNode.insertBefore(newNodeTop, header); header.classList.add(css); } setTimeout(() => { let height = header.offsetHeight + 1; //高度 + 1 以防有小數點 newNodeTop.style.height = height + 'px'; }, 0) } },
    watch: {
      oldToNew(newVal, oldVal) {
        if(newVal.length !== oldVal.length) {
          this.$refs.sticky_.sticky()
        }
      }
    }, } } </script>
<style scoped>
.header_sticky { width: 100%; position: sticky; position: -webkit-sticky; top: 0; z-index: 100; transition: height 1s; -moz-transition: height 1s; -webkit-transition: height 1s; -o-transition: height 1s; } .sticky_ { width: 100%; position: fixed; position: -webkit-fixed; top: 0; z-index: 100; }

</style>
 
        
 
        

使用


  
<sticky-header ref="sticky_"> <!-- contents --> </sticky-header>
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM