ECMAScript 6之后JavaScript开始支持class类了。以前写js代码一直很头疼。现在感觉也挺好写的,要不考虑兼容性的话,真和写python没多大区别了。
写了一个广告切换脚本,自定义pc端和移动端的广告。每60秒显示一次广告,广告代码从某下载站扒的。可以扩展Ad类的AdControl()方法来改进广告显示逻辑,最好将AdControl()方法分离到Ad类之外,这样结构更合理。
参考: 阮一峰:ECMAScript 6 入门](http://es6.ruanyifeng.com/#docs/class)
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Javascript 广告弹窗切换测试</title>
<link rel="stylesheet" href="base.css">
<script src="main.js"></script>
</head>
<body>
<a href="list.html" target="_blank">list page</a>
<a href="detail.html" target="_blank">detail page</a>
</body>
</html>
JavaScript
/**
* Created by cl1844@gmail.com on 17.2.19.
*/
/** class 仅在支持ECMAScript 6的浏览器中有效,生产环境一般需要用工具转换成EC5的代码 **/
function randomElement(myArray) {
return myArray[Math.floor(Math.random() * myArray.length)];
}
function checkUserAgent() {
var ua = navigator.userAgent;
//var device = 'pc';
if (ua.includes('iP')) {
device = 'iphone';
}
else if (ua.includes('Android')) {
device = 'android';
}
else if (ua.toLowerCase().includes('bot') || ua.toLowerCase().includes('spider')) {
device = 'spider';
}
else {
device = 'pc';
}
return device;
}
class Ad {
constructor(ad1=null,ad2=null,ad3=null,ad4=null) {
this.ad1 = ad1;
this.ad2 = ad2;
if (ad3) {
this.ad3 = ad3;
}
if (ad4) {
this.ad4 = ad4;
}
}
showAd() {
var ad = randomElement(Object.values(this));
console.log(ad);
console.log(Object.values(this));
document.write(ad);
this.setCookie();
}
setCookie() {
var myCookie = document.cookie.replace(/(?:(?:^|.*;\s*)showad\s*\=\s*([^;]*).*$)|^.*$/, "$1");
if (myCookie == ''){
myCookie = 1;
}
else {
myCookie = parseInt(myCookie) + 1;
}
document.cookie = 'showad='+myCookie + '; max-age=120';
}
AdControl() {
var myCookie = document.cookie.replace(/(?:(?:^|.*;\s*)showad\s*\=\s*([^;]*).*$)|^.*$/, "$1");
var device = checkUserAgent();
if (device == 'spider') {
}
else if (device == 'pc' && myCookie = '') {
this.showAd();
}
else if (device == 'android'&& myCookie = '') {
this.showAd();
}
}
}
var ad1 = '<script src="http://v.6dvip.com/ge/?s=47688"></script>';
var ad2 = '<script src="http://89.8ox.cn/pge/?s=46212"></script>';
pc = new Ad(ad1,ad2);
pc.AdControl();