首先看一下项目的预览图
PC浏览器
音乐播放器切歌功能的实现
html部分:
<audio src="" autoplay="true"></audio>
我准备了5首歌,当歌曲放完时要自动切换到下一首,这就要靠JS实现了:
var oPlayer = document.getElementsByTagName('audio')[0];
oPlayer.src = "music/"+ Math.ceil(Math.random()*5) +".mp3";
oPlayer.addEventListener('timeupdate', function() {
if (oPlayer.currentTime === oPlayer.duration ) {
oPlayer.src = "music/"+ Math.ceil(Math.random()*5) +".mp3";
}
});
绑定一个事件监听函数来实现一首歌曲播放完毕自动切换到下一首,当然也可以利用这个函数写一个播放进度。
DIV居中
给父元素设置相对定位,就可以这样写子元素的样式来使其居中:
.content {
width: 800px;
height: 600px;
position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
}
手机orPC?
我的意图是尽可能使用PC访问,但是也允许点击“仍然要试试?”在手机端使用。这里就涉及到浏览器的判断,用jQurey就可以实现:
$(document).ready(function () {
$('.nopc').hide();
//pc判断
if(navigator.userAgent.match(/mobile/i)) {
$('.nopc').show(200);
$('.expla').hide(200);
$('#btn').hide(200);
}
//手机端访问
$('#mobileBtn').click(function () {
$('.nopc').hide(600);
$('.expla').show(800);
$('#btn').show(1000);
});
});
限于水平,目前想不到更好的写法。
Vue部分
Vue提供一个更通用的方法通过watch选项,来响应数据的变化。当你想要在数据变化响应时,执行异步操作或开销较大的操作,这是很有用的。
以上摘自Vue文档
HTML结构:
<section id="app">
<input type="text" value="" placeholder="亲,请输入身份证号" ref="inputInfo"
v-model="information">
<button v-on:click="getInfo">查询</button>
<p v-if="seen2">{{ tip }}</p>
<div class="info" v-if="seen">
<p>姓名:<span>{{ name }}</span></p>
<p>年龄:<span>{{ age }}</span></p>
<p>性别:<span>{{ sex }}</span></p>
<p>生日:<span>{{ birthday }}</span></p>
<p>地址:<span>{{ address }}</span></p>
</div>
</section>
JS部分:
var vm = new Vue({
el: '#app',
data: {
information: '',
name: null,
age: null,
birthday: null,
tip: null,
seen: false,
seen2: false
},
// 如果 information 发生改变,这个函数就会运行
watch: {
information: function (newInfo) {
//显示tip
this.seen2 = true
this.tip = "请输入18位身份证号"
}
},
methods: {
getInfo: function () {
var value = this.$refs.inputInfo.value
if (value.length !== 18) {
this.tip = "身份证号应为18位"
} else {
var url = 'https://route.showapi.com/25-3?id='+value+'&showapi_appid=32653&showapi_sign=d04acc7ae0d741249112a1227a045e3b'
//接下来就是请求数据了,记得要在此之前引入vue-resource.js
this.$http.get(url)
.then(function(res) {
var data = res.body.showapi_res_body.retData
this.age = new Date().getFullYear() - value.substr(6,4)
this.birthday = data.birthday
this.address= data.address
if (data.sex === 'M') {
this.name = '单身' + this.age + '年的单身狗'
this.sex = '男'
} else {
this.name = '萌萌哒的小仙女'
this.sex = '女'
}
//关闭tip,显示结果
this.seen2 = false
this.seen = true
})
}
}
}
});
结束语
到此为止,核心的部分就总结完了。最后安利一下:Vue比Angular好上手多了!点击下方地址就可以看这次的demo哦。
点我点我