收藏
评论

自定义 img 标签 组件

<!--components/img/img.wxml-->

<imgComponent class="{{isLoaded||!src?'loaded':'loading'}} {{isError||!src?'error ext-error-class':''}}" data-state='{{isError?"error":"normal"}}'>

<imgPlaceholder />

  <image wx:if="{{src}}" src='{{src}}' mode="{{mode}}" lazy-load='{{lazyLoad}}' binderror='error' bindload="load" />

</imgComponent>


/* components/img/img.wxss */

img{

  display: inline-block;

  overflow: hidden;

  box-sizing: border-box;

}

imgComponent{

  position: relative;

  display: block;

  height: 100%;

  z-index: 0;

}

imgComponent>imgPlaceholder{

  display: block;

  position: absolute;

  top: 0;

  z-index: 1;

  background: var(--img-placeholder,#EEEEEE) no-repeat center;

  background-size: var(--img-placeholder-size,100% 100%);

  pointer-events: none;

  width: 100%;

  height: 100%;

}

imgComponent>image{

  vertical-align: top;

  min-width: 100%;

  min-height: 100%;

  max-height: 100%;

  max-width: 100%;

}

imgComponent.loaded:not(.error)>imgPlaceholder{

  opacity: 0;

  z-index: -1;

  /* transition: opacity 200ms,z-index 200ms; */

}


imgComponent.error>imgPlaceholder{

  background: var(--img-error-placeholder,#EEEEEE) no-repeat center;

  background-size: var(--img-error-placeholder-size,contain);

}

imgComponent.error imgPlaceholder::before{

    content: "加载图片失败";

    position: absolute;

    top: 0;

    left: 0;

    right: 0;

    bottom: 0;

    margin: auto;

    height: 10px;

    font-size: 10px;

    color: #FFF;

    text-align: center;

    text-shadow: 0 0 10px rgba(0,0,0,0.8),0 0 10px rgba(0,0,0,0.8);

}

/* imgComponent.loading imgPlaceholder::before{

    content: "正在加载图片";

} */

// components/img/img.js

Component({

    /**

     * 组件的属性列表

     */

    properties: {

        src: String,

        mode: {

            type: String,

            value: "widthFix"

        },

        lazyLoad: {

            type: Boolean,

            value: false

        }

    },

    externalClasses: ['ext-error-class'],

    /**

     * 组件的初始数据

     */

    data: {},


    /**

     * 组件的方法列表

     */

    ready() {},

    methods: {

        error(e) {

            if (this.data.isLoaded) {

                return

            }

            this.setData({

                isLoaded: true,

                isError: true

            });

            this.triggerEvent("error", e);

        },

        load(e) {

            if (this.data.isLoaded) {

                return

            }

            this.setData({

                isLoaded: true,

                isError: false

            });

            this.triggerEvent("load", e);

        }

    }

})


最后一次编辑于  2018-09-01
赞 0
收藏