文档拉到最底部才能操作按钮

2019-09-26  本文已影响0人  钱英俊真英俊

Vue的项目, 弹窗的文档是用iframe引入html显示的,但新增了文档必须拉到最底部才能操作按钮,iframe无法监听到scroll事件

需求

实现如下:

<template lang="pug">
  .main-wrap
    el-dialog(
      v-if="isShow" // 每次展示都重新渲染以便滚动条复原
      title="Document"
      width="700px" // 固定宽度以便确认scrollTop
      :visible.sync="isShow")
      p.content#content(v-html="text" @scroll="scroll") // 文档展示
      .footer(slot="footer" v-if="isCheck")
        el-button(@click="isShow = false") {{$t('common.cancel')}}
        el-button(
          :disabled="disabled"
          type="primary"
          @click="confirm") {{$t('common.loan')}}
  
</template>

<script>
export default {
  data () {
    return {
      isShow: false, //是否显示弹窗
      text: '', // 文档内容
      disabled: true // 按钮是否可以操作
    }
  },

  methods: {
// 每次显示弹窗的时候按钮不能操作复位
    toShow (row) {
      this.disabled = true
    },
// 获取文档内容并解析
    async getHtml () {
    // 判断环境
      const location = window.location
      let url = ''
      let hostname = location.hostname
      if (hostname === 'localhost') {
        url = `${location.origin}/static/doct.html`
      } else {
        url = `${location.origin}/dist/static/dot.html`
      }
      let headers = new Headers()
      // 设置fetch请求头
      headers.append('Content-Type', 'text/plain')
      fetch(url, {
        headers
      }).then((res) => {
        return res.text()
      }).then(res => {
        this.text = res
      })
    },
// 判断文档滚动位置
    scroll (v) {
      if (!this.disabled) return false // 如果到底部就再设置了
      let top = v.target.scrollTop
      this.disabled = (v.target.scrollHeight - top !== v.target.clientHeight) // 到底部到话就可操作
    }
  },
  async  mounted () {
    await this.getHtml()
  }

}
</script>
<style scoped>
// 文档内容样式
.content {
  border: 3px solid #ccc;
  padding: 15px;
  height: 400px;
  overflow-y: scroll;
}

</style>
原理:
  1. 通过fetch获取远程html并解析为text;
  2. 通过v-html把解析过后的字符串渲染到模板中;
    3.监听文档的scroll事件并判断文档的scrollTop是否已经到底部,同步到按钮的disabled
判断元素是否到底部

element.scrollHeight - element.scrollTop === element.clientHeight

上一篇下一篇

猜你喜欢

热点阅读