使用JS監聽DOM元素的屬性及動畫、CSS過渡


這里我們要是用的JS的api,MutationObserver,進行監聽DOM元素的監聽

注意:MutationObserver如果用來監聽寬高等,只能監聽其內部屬性,比如style中的width屬性,無法監聽class中的width改變
如果想要監聽動畫或者CSS過渡事件,MutationObserver是無法監聽到的,可以使用addEventListener中的監聽方法

監聽動畫或CSS過渡


<style>
  #demo{
    width:200px;
    transition: width 0.5s ease-out;
  };
  #demo:hover{
    width:0;
  }
</style>

<div id='demo'>我是DEMO</div>

var element = document.getElementById('demo')
//監聽過渡完成transitionend    監聽動畫完成animationend
element.addEventListener('transitionend', handle, false)
function handle(){
    console.log('css事件過渡效果完成');
}

注意:元素從display:none 到block opacity從0到1,無法觸發過渡效果。
無法觸發過渡效果原因:
元素從none到block,剛生成未能即時渲染,導致過渡失效。所以需要主動觸發頁面重繪,刷新DOM。
頁面重繪可以通過改變一些CSS屬性來觸發,例如:offsetTop、offsetLeft、offsetWidth、scrollTop等。

使用MutationObserver監聽DOM屬性

配置MutationObserver

MutationObserver使用示例

<template>

  <div class="container">
    <div class="resize-element">
      改變大小試試
    </div>
    <div class="resize-record">
      觸發了{{firedNum}}次resize事件。
    </div>
  </div>
</template>

<script>
  export default {
    name: "test",
    data () {
      return {
        observer: null,
        firedNum: 0,
      }
    },
    mounted () {
      let MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver
      let element = document.querySelector('.resize-element');

      this.observer = new MutationObserver((mutationList) => {
        for (let mutation of mutationList) {
          console.log(mutation)
        }
        let width = getComputedStyle(element).getPropertyValue('width')
        console.log(width)
        this.firedNum += 1;
      })
      this.observer.observe(element, { attributes: true, attributeFilter: ['style'], attributeOldValue: true })
    },
    beforeDestroyed () {
      // disconnect()  阻止 MutationObserver 實例繼續接收的通知,直到再次調用其observe方法,該觀察者對象包含的回調函數都不會再被調用。
      // takeRecords() 從MutationObserver的通知隊列中刪除所有待處理的通知,並將它們返回到一個MutationRecord對象構成的新數組中。

      //銷毀DOM監聽
      if (this.observer) {
        this.observer.disconnect()
        this.observer.takeRecords()
        this.observer = null
      }
    }
  }
</script>

<style scoped>
  .container{
    position:relative
  }
  .resize-element{
    position: absolute;
    top :50%;
    left :50%;
    height: 10rem;
    width :10rem;
    overflow: hidden;
    /*通過resize屬性改變DOM中的style,或者直接使用js更改Style*/
    resize :both;
    display :block;
    box-shadow: 0 0 1px 1px #3361D8;
  }
</style>


免責聲明!

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



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