在weex中,使用图片也没有想象中那么简单,在html里有<image>,css里面有background-image,但是weex中能使用的图片的东西也就只有image。而且也不好使,所以在这里阐述一下<image>.
- 怎么获取图片的实际高度
- 怎么作为背景图片
怎么获取图片的实际高度
weex中,使用图片是明码标价width,height。如果这两个缺了再漂亮的图片也不会显示。但是,有时候我就想偷懒不想写宽高那么怎么办?大概的思路其实很简单,但是没多少人发现,那就是image中的onload事件。
实现思路大约是:
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
| <template> <image @load="onLoad" ref="img" :src="src"/> </template> <script> export default { data: () => ({ width: 0, height:0 }), computed: { getStyle () { return { width: this.width + 'px', height: this.height + 'px' } } }, methods: { onLoad (e) { if (e.success && e.size && e.size.naturalWidth > 0 ) { this.width = e.size.naturalWidth * this.scale this.height = e.size.naturalHeight * this.scale } } } } </script>
|
怎么作为背景图片
有时候我们也想把图片作为背景图片,在web里,可以直接使用background-image。那么,在weex,不用想了,不支持这样
那么我想到用绝对定位 —— image 配合 position:absolute 来实现。
实现思路大约是:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <style scoped> .box__container--img{ position: absolute; top: 0; left:0; } .box__container--text{ margin-left: 30px; } </style> <template> <div class="box__container"> <image class="box__container--img"></image> <text class="box__container--text">菜单</text> </div> </template> <script> export default { } </script>
|