get-element-by-id.uvue 2.0 KB
Newer Older
1
<template>
DCloud-yinjiacheng's avatar
DCloud-yinjiacheng 已提交
2
  <page-head id="page-head" title="getElementById"></page-head>
3
  <view style="margin: 0 15px;">
DCloud-yinjiacheng's avatar
DCloud-yinjiacheng 已提交
4 5 6 7 8 9 10 11 12 13 14 15 16 17
    <text id="text">this is text</text>
    <view id="view" class="uni-common-mt" style="border: 1px solid red">this is view</view>
    <button class="uni-btn" @click="changePageHeadBackgroundColor">
      修改 page-head 背景色
    </button>
    <button class="uni-btn" @click="changeTextColor">
      修改 text 字体颜色
    </button>
    <button class="uni-btn" @click="changeViewStyle">
      修改 view 宽高及背景色
    </button>
    <button class="uni-btn" @click="goMultipleRootNode">
      跳转多根节点示例
    </button>
18 19 20 21
  </view>
</template>

<script lang="uts">
DCloud-WZF's avatar
DCloud-WZF 已提交
22 23 24 25 26 27
  export default {
    data() {
      return {
        checked: false,
        homePagePath: '/pages/tabBar/component',
        launchOptionsPath: '',
28
      }
DCloud-WZF's avatar
DCloud-WZF 已提交
29
    },
DCloud-WZF's avatar
DCloud-WZF 已提交
30
    methods: {
31
      getElementByNotExistId() : Element | null {
DCloud-WZF's avatar
DCloud-WZF 已提交
32 33 34 35
        return uni.getElementById('not-exist-id')
      },
      changePageHeadBackgroundColor() {
        const pageHead = uni.getElementById('page-head')!
雪洛's avatar
雪洛 已提交
36
        pageHead.style.setProperty('background-color', 'red')
DCloud-WZF's avatar
DCloud-WZF 已提交
37 38
      },
      changeTextColor() {
雪洛's avatar
雪洛 已提交
39
        const text = uni.getElementById('text')!
雪洛's avatar
雪洛 已提交
40
        text.style.setProperty('color', 'red')
雪洛's avatar
雪洛 已提交
41
      },
DCloud-WZF's avatar
DCloud-WZF 已提交
42 43 44
      changeViewStyle() {
        const view = uni.getElementById<UniViewElement>('view')
        if (view !== null) {
雪洛's avatar
雪洛 已提交
45 46 47
          view.style.setProperty('width', '90%')
          view.style.setProperty('height', '50px')
          view.style.setProperty('background-color', '#007AFF')
DCloud-WZF's avatar
DCloud-WZF 已提交
48 49 50 51
        }
      },
      goMultipleRootNode() {
        uni.navigateTo({ url: '/pages/API/get-element-by-id/get-element-by-id-multiple-root-node' })
DCloud-WZF's avatar
DCloud-WZF 已提交
52 53 54 55 56
      },
      //自动化测试获取text元素的offsetLeft属性值
      getTextOffsetLeft() : number {
        const text = uni.getElementById('text')!
        return text.offsetLeft
DCloud-WZF's avatar
DCloud-WZF 已提交
57
      }
58 59
    }
  }
DCloud-WZF's avatar
DCloud-WZF 已提交
60
</script>