get-element-by-id.uvue 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <template>
  2. <page-head id="page-head" title="getElementById"></page-head>
  3. <view style="margin: 0 15px;">
  4. <text id="text">this is text</text>
  5. <view id="view" class="uni-common-mt" style="border: 1px solid red">this is view</view>
  6. <button class="uni-btn" @click="changePageHeadBackgroundColor">
  7. 修改 page-head 背景色
  8. </button>
  9. <button class="uni-btn" @click="changeTextColor">
  10. 修改 text 字体颜色
  11. </button>
  12. <button class="uni-btn" @click="changeViewStyle">
  13. 修改 view 宽高及背景色
  14. </button>
  15. <button class="uni-btn" @click="goMultipleRootNode">
  16. 跳转多根节点示例
  17. </button>
  18. </view>
  19. </template>
  20. <script lang="uts">
  21. export default {
  22. data() {
  23. return {
  24. checked: false,
  25. homePagePath: '/pages/tabBar/component',
  26. launchOptionsPath: '',
  27. }
  28. },
  29. methods: {
  30. getElementByNotExistId() : Element | null {
  31. return uni.getElementById('not-exist-id')
  32. },
  33. changePageHeadBackgroundColor() {
  34. const pageHead = uni.getElementById('page-head')!
  35. pageHead.style.setProperty('background-color', 'red')
  36. },
  37. changeTextColor() {
  38. const text = uni.getElementById('text')!
  39. text.style.setProperty('color', 'red')
  40. },
  41. changeViewStyle() {
  42. const view = uni.getElementById<UniViewElement>('view')
  43. if (view !== null) {
  44. view.style.setProperty('width', '90%')
  45. view.style.setProperty('height', '50px')
  46. view.style.setProperty('background-color', '#007AFF')
  47. }
  48. },
  49. goMultipleRootNode() {
  50. uni.navigateTo({ url: '/pages/API/get-element-by-id/get-element-by-id-multiple-root-node' })
  51. },
  52. //自动化测试获取text元素的offsetLeft属性值
  53. getTextOffsetLeft() : number {
  54. const text = uni.getElementById('text')!
  55. return text.offsetLeft
  56. }
  57. }
  58. }
  59. </script>