element-get-attribute.uvue 2.0 KB
Newer Older
Anne_LXM's avatar
Anne_LXM 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
<template>
  <view>
    <view id="box" ref="box" style="padding: 20rpx;">
      <text class="uni-title-text">元素的id:{{ attrId }}</text>
      <text class="uni-title-text">元素的style:{{ attrStyle }}</text>
      <text class="uni-subtitle-text">小程序端:getAttribute 获取元素的属性值,目前仅支持id、style</text>
    </view>
    <button @click="getAttributeId">getAttribute获取元素的id</button>
    <button @click="setStyle">setProperty设置背景色</button>
    <button @click="getAttributeStyle">getAttribute获取元素的style</button>
    <scroll-view ref="scrollView" class="scroll-view_H" direction="horizontal">
      <view class="scroll-view-item_H uni-bg-red"><text class="text">A</text></view>
      <view class="scroll-view-item_H uni-bg-green"><text class="text">B</text></view>
      <view class="scroll-view-item_H uni-bg-blue"><text class="text">C</text></view>
    </scroll-view>
    <button @click="scrollTo">scrollTo设置left滚动200px</button>
  </view>
</template>
<script>
  export default {
    data() {
      return {
        boxTarget: null as null | UniElement,
        scrollViewTarget: null as null | UniElement,
        attrId: '',
        attrStyle:''
      }
    },
    onReady() {
      this.boxTarget = this.$refs['box'] as UniElement
      this.scrollViewTarget = this.$refs['scrollView'] as UniElement;
    },
    methods: {
      scrollTo() {
        this.scrollViewTarget!.scrollTo({
          left: 200
        })
      },
      getAttributeId() {
        this.attrId = this.boxTarget.getAttribute('id')
      },
      setStyle() {
        this.boxTarget.style.setProperty("background-color", "#FFF000")
      },
      getAttributeStyle() {
        this.attrStyle = this.boxTarget.getAttribute('style')
      }
    }
  }
</script>
<style>
  .scroll-view_H {
    width: 100%;
    flex-direction: row;
    margin-top:30rpx;
  }
  .scroll-view-item_H {
    width: 100%;
    height: 150px;
    justify-content: center;
    align-items: center;
  }
  .text {
    font-size: 18px;
    color: #ffffff;
  }
</style>