vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > vue监听dom节点宽高变化

Vue实现监听dom节点宽高变化方式

作者:風灬雲

这篇文章主要介绍了Vue实现监听dom节点宽高变化方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

原生js方法

该方法适用所有vue项目,原生js开发的思维

    <div ref="datas">
            <div class="scroll_box" ref="scroll" style="width:20%;height: 20%;overflow:scroll;position: absolute;left: 0;top: 0;background-color: #000;">
                      <div class="scroll_child" style="width:300%;height: 300%;"></div>
            </div>
          <div class="scroll_box2" ref="scroll2" style="width:20%;height: 20%;overflow:scroll;position: absolute;left: 0;top: 0;background-color: #000;">
              <div class="scroll_child" style="width:300px;height: 300px;"></div>
          </div>
    </div>
mounted(){
        // 监听节点宽高变小
        (this.$refs.scroll as HTMLElement).scrollTop = 1000;
        (this.$refs.scroll as HTMLElement).scrollLeft = 1000;
        (this.$refs.scroll as HTMLElement).addEventListener('scroll', () => {
            this.width = ((this.$refs.datas as Vue).$el as HTMLElement).offsetWidth;
            (this.$refs.scroll2 as HTMLElement).scrollTop = 1000;
            (this.$refs.scroll2 as HTMLElement).scrollLeft = 1000;
        });
        
        // 监听节点宽高变大
        (this.$refs.scroll2 as HTMLElement).scrollTop = 1000;
        (this.$refs.scroll2 as HTMLElement).scrollLeft = 1000;
        (this.$refs.scroll2 as HTMLElement).addEventListener('scroll', () => {
            this.width = ((this.$refs.datas as Vue).$el as HTMLElement).offsetWidth;
            (this.$refs.scroll as HTMLElement).scrollTop = 1000;
            (this.$refs.scroll as HTMLElement).scrollLeft = 1000;
        })
}

element-ui element-resize-detector插件

vue + element 开发项目时的首选,简单有效

<div ref="datas"></div>
mounted(){
        let erd = elementResizeDetectorMaker();
        erd.listenTo((this.$refs.datas as Vue).$el,  (element: HTMLElement) => {
            this.width = element.offsetWidth;
        })
}

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文