ECMAScript 6之后JavaScript開始支持class類了。以前寫js代碼一直很頭疼∠胨В現(xiàn)在感覺也挺好寫的场靴,要不考慮兼容性的話,真和寫python沒多大區(qū)別了港准。
寫了一個廣告切換腳本旨剥,自定義pc端和移動端的廣告。每60秒顯示一次廣告浅缸,廣告代碼從某下載站扒的轨帜。可以擴(kuò)展Ad類的AdControl()方法來改進(jìn)廣告顯示邏輯衩椒,最好將AdControl()方法分離到Ad類之外蚌父,這樣結(jié)構(gòu)更合理。
參考: 阮一峰: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的瀏覽器中有效毛萌,生產(chǎn)環(huán)境一般需要用工具轉(zhuǎn)換成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();