当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 微信小程序组件 marquee实例详解

微信小程序组件 marquee实例详解

2017年12月12日  | 移动技术网IT编程  | 我要评论

微信小程序组件 marquee实例详解

1. marquee标签

html是有marquee标签的,可以实现跑马灯效果,但小程序没有,所以要实现。这里考虑使用css3的animation实现。

html的marquee是这样使用的。

<marquee direction="left" behavior="scroll" scrollamount="1" scrolldelay="0" loop="-1" width="200" height="50" bgcolor="#0099ff" hspace="10" vspace="10">
   hello world
</marquee>

2. wxml

<view class="marquee_container" style="--marqueewidth--:{{-marquee.width}}em">
  <view class="marquee_text">{{marquee.text}}</view>
</view>

传入wxml的是个json对象

marquee:{
  width:12,
  text:'hello world'
}

而那个奇怪的--marqueewidth是给@keyframes传的变量。内联设置变量,css文件中也可以获取到该变量。

3. wxss

@keyframes around {
  from {
   margin-left: 100%;
  }
  to {
   margin-left: var(--marqueewidth--);// var接受传入的变量
  }
 }

.marquee_container{
 background-color: #0099ff;
 height: 1.2em;
 position: relative;
 width: 100%;
}
.marquee_container:hover{
 animation-play-state: paused; // 不起作用
}
.marquee_text{
 display: inline-block;
 white-space: nowrap;
 animation-name: around;
 animation-duration: 5s;
 animation-iteration-count: infinite;
 animation-timing-function:linear;
}

4. js

export default {
 getwidth:(str)=>{
  return [].reduce.call(str, (pre, cur, index, arr) => {
   if (str.charcodeat(index) > 255) {// charcode大于255是汉字
    pre++;
   } else {
    pre += 0.5;
   }
   return pre;
  }, 0);
 },
 getduration:(str)=>{// 保留,根据文字长度设置时间
  return this.getwidth()/10;
 }
}

以上是组件的封装。

5. 使用

// wxml
<include src="../component/marquee/marquee.wxml" />
// wxss
@import "../component/marquee/marquee.wxss";
// js
import marquee from '../component/marquee/marquee.js';

var options = object.assign(marquee, {
 data: {
  motto: 'hello world',
  userinfo: {},
  marquee: { text: '你好,中国!hello,world!' }
 },
 onload: function () {
  // ...

  const str = this.data.marquee.text;
  const width = this.getwidth(str);
  console.log('width',width);
  this.setdata({ [`${'marquee'}.width`]: width });
 }
});
page(options);

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网