Blame view

public/js/common.js 13.9 KB
毕凯 authored
1 2 3 4 5
/**
 * 页面公共逻辑
 * @author: xuqi<qi.xu@yoho.cn>
 * @date: 2015/10/21
 */
lijing authored
6
let $ = require('yoho-jquery');
7
let yohoCookie = require('yoho-cookie');
毕凯 authored
8
lijing authored
9
let $footer = $('#yoho-footer'),
毕凯 authored
10 11 12
    $yohoPage = $('.yoho-page'),
    $header = $('.yoho-header');
郝肖肖 authored
13
// 为您优选-40位随机数指纹请求id
lijing authored
14
let RECID = (new Date().getTime() + '_H5_YOHOBUY_' + Math.floor(Math.random() * 1000000 + 1000000) +
郝肖肖 authored
15 16
    '_' + Math.floor(Math.random() * 1000000 + 1000000));
lijing authored
17
let _ChannelVary = {
沈志敏 authored
18 19 20 21 22
    boys: 1,
    girls: 2,
    kids: 3,
    lifestyle: 4
};
23
zhangxiaoru authored
24 25
require('./common/share');
毕凯 authored
26
function cookie(name) {
沈志敏 authored
27
28 29
    // var re = new RegExp(name + '=([^;$]*)', 'i'),
    //     matchPattern = '$1';
王水玲 authored
30
31 32 33 34 35 36 37 38 39 40 41
    // if (name === '_UID') {
    //     return decodeURIComponent(re.test(document.cookie) ? RegExp[matchPattern] : '');
    // }

    // try {
    //     return re.test(decodeURIComponent(document.cookie)) ? RegExp[matchPattern] : '';
    // } catch (e) {
    //     return decodeURIComponent(re.test(document.cookie) ? RegExp[matchPattern] : '');
    // }

    return yohoCookie.get(name);
毕凯 authored
42 43 44
}

function setCookie(name, value, options) {
lijing authored
45
    let expires = '',
毕凯 authored
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
        path,
        domain,
        secure,
        date;

    if (typeof value !== 'undefined') {
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }

        if (options.expires &&
            (typeof options.expires === 'number' || options.expires.toUTCString)) {
            if (typeof options.expires === 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString();
        }
        path = options.path ? '; path=' + options.path : '';
        domain = options.domain ? '; domain=' + options.domain : '';
        secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    }
}

function isCookiesEnabled() {
lijing authored
76
    let cookieEnabled = (navigator.cookieEnabled) ? true : false;
毕凯 authored
77 78 79 80 81 82 83 84 85 86

    if (typeof navigator.cookieEnabled === 'undefined' && !cookieEnabled) {
        document.cookie = 'testcookie';
        cookieEnabled = (document.cookie.indexOf('testcookie') !== -1) ? true : false;
    }

    return (cookieEnabled);
}

function getUser() {
lijing authored
87
    let c = cookie('_UID'),
毕凯 authored
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
        user;

    if (typeof c === 'undefined') {
        return 0;
    }

    user = c.split('::');

    if (typeof user === 'undefined' || user.length < 4) {
        return 0;
    }

    return user;
}

function getUid() {
lijing authored
104
    let user = getUser();
毕凯 authored
105 106 107 108 109 110 111 112 113

    if (user === 0) {
        return 0;
    }

    return user[1];
}

function getShoppingKey() {
lijing authored
114
    let c = cookie('_g');
毕凯 authored
115 116 117 118 119 120 121 122 123 124

    if (typeof c === 'undefined') {
        return '';
    }

    return JSON.parse(c).k;
}

// 根据页面内容重新设置通用底部的显示
function rePosFooter() {
lijing authored
125
    let winH;
毕凯 authored
126 127 128 129 130

    if ($footer.length === 0) {
        return;
    }
zhangxiaoru authored
131 132
    $footer.addClass('bottom');
ccbikai(👎🏻🍜) authored
133
    if ($footer.css('position') === 'static') {
134 135 136
        $footer.css('position', '');
    }
毕凯 authored
137 138
    winH = Math.min($(window).height(), window.screen.availHeight);
zhangxiaoru authored
139
    if ($('body').height() >= winH - parseInt($footer.css('height'), 0)) {
毕凯 authored
140 141
        $footer.removeClass('bottom');
    }
142
    $footer.show();
毕凯 authored
143 144 145 146 147 148 149 150 151
}

/**
 *
 * add extra margin-bottom for footer to show yoho copyright when there is fixed bottom element on page
 * @param {String} The jquery selecor of the fixed bottom element
 * @return undefined
 */
function reMarginFooter(fixedElement) {
lijing authored
152
    let fixedElH = $(fixedElement).outerHeight();
毕凯 authored
153 154 155 156 157 158

    if (fixedElement) {
        $footer.css('margin-bottom', fixedElH + 'px');
    }
}
郝肖肖 authored
159
function queryString() {
lijing authored
160
    let vars = [],
郝肖肖 authored
161 162
        hash,
        i;
lijing authored
163
    let hashes = window.location.search.slice(1).split('&');
郝肖肖 authored
164 165 166 167 168 169 170 171 172

    for (i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
陈峰 authored
173 174 175
/**
 * 对象字段排序
 */
ccbikai(👎🏻🍜) authored
176
function mapSort(obj) {
陈峰 authored
177 178 179 180 181 182 183 184 185 186 187 188
    if (!obj) {
        return {};
    }
    let data = {};

    Object.keys(obj).sort().forEach(k => {
        data[k] = obj[k];
    });

    return data;
}
郝肖肖 authored
189 190 191 192 193
// 给jQuery 扩展 queryString函数
$.extend({
    queryString: queryString
});
毕凯 authored
194 195
// 页面通用底部位置及status设置
(function() {
lijing authored
196
    let $op = $footer.children('.op-row'),
197 198
        $backToTop = $('.back-to-top'),
        $floatTop = $('.float-top');
毕凯 authored
199
lijing authored
200
    let user = getUser();
毕凯 authored
201
202 203 204
    setTimeout(function() {
        rePosFooter(); // 计算底部位置
    }, 500);
毕凯 authored
205 206 207 208 209

    if (user === 0) {

        // 未登录
        $op.prepend(
郭成尧 authored
210
            '<a href="/signin.html?refer=' + location.href + '" rel="nofollow">登录</a>' +
毕凯 authored
211
            '<span class="sep-line">|</span>' +
郭成尧 authored
212
            '<a href="/reg.html" rel="nofollow">注册</a>'
毕凯 authored
213 214 215 216 217 218
        );
    } else {

        // 已登录
        $op.prepend(
            '<span>Hi,</span>' +
219
            '<a class="user-name" href="/home?tmp=' + Math.random() + '">' + user[0] + '</a>' +
220
            '<span class="sep-line">|</span>' +
221
            '<a href="/passport/signout/index">退出</a>'
毕凯 authored
222 223 224 225
        );
    }

    if ($backToTop.length > 0) {
226
        $backToTop.on('touchend touchcancel', function(e) {
毕凯 authored
227
            $(window).scrollTop(0);
228
            e.preventDefault();
毕凯 authored
229 230 231
            return false;
        });
    }
232
    if ($floatTop.length > 0) {
陈峰 authored
233
        $floatTop.on('click', function(e) {
234
            $(window).scrollTop(0);
陈峰 authored
235
            e.preventDefault();
236 237 238
            return false;
        });
    }
毕凯 authored
239 240

    $footer.removeClass('hide');
郝肖肖 authored
241
郝肖肖 authored
242
    // 单击下载按钮 - 接受微信商城或者第三方来源的数据埋点信息
243
    let unionType = queryString().union_type || '';
ccbikai(👎🏻🍜) authored
244
245 246
    if (unionType) {
        setCookie('unionTypeYas', unionType, {
沈志敏 authored
247 248
            path: '/'
        });
郝肖肖 authored
249 250
    }
251 252 253 254 255 256 257 258 259 260 261
    /*
    关于yas种cookies的逻辑澄清:

    1. yas的关于渠道号的cookies的key 是 mkt_code
    2. mkt_code 失效时间为7天
    3. 如果url后面加union_type,mkt_code 在微信下是覆盖的,其他端不覆盖
    4. 如果mkt_code=100000000000349,则直接覆盖成对应的渠道号
    5. yas的cookies 种在 .yohobuy.com 根域下

    周奇琪
毕凯 authored
262 263
    mkt_code 控制移动到 YAS 2017.07.13
    */
264
毕凯 authored
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284
    // let isWechat = /micromessenger/i.test(navigator.userAgent || '');
    // let mktc = queryString().mkt_code || queryString().union_type || '';

    // function saveMktCode() {
    //     if (mktc) {
    //         setCookie('mkt_code', mktc, {
    //             path: '/',
    //             domain: 'yohobuy.com',
    //             expires: 7 // 7天
    //         });
    //     }
    // }

    // if (isWechat) {
    //     saveMktCode();
    // } else {
    //     if (!cookie('mkt_code') || mktc === '100000000000349') {
    //         saveMktCode();
    //     }
    // }
285
ccbikai(👎🏻🍜) authored
286 287 288
    // 尝试打开 APP
    require('./common/open-app');
毕凯 authored
289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
}());

$header.on('touchstart', 'a', function() {
    $header.find('a').removeClass('highlight');
    $(this).addClass('highlight');
}).on('touchend touchcancel', 'a', function() {
    $(this).removeClass('highlight');
});

$yohoPage.on('touchstart', '.tap-hightlight', function() {
    $(this).siblings('.tap-hightlight').removeClass('highlight');
    $(this).addClass('highlight');
}).on('touchend touchcancel', '.tap-hightlight', function() {
    $(this).removeClass('highlight');
});
郭成尧 authored
305
$('.new-nav-home').on('touchstart', function(e) {
毕凯 authored
306
    $('.homebuttom').toggleClass('hide');
郭成尧 authored
307 308
    e.preventDefault();
    e.stopPropagation();
毕凯 authored
309 310
});
311 312 313 314
// 点击关闭头部菜单
$('.main-wrap').on('click', '*', (e) => {
    let $this = $(e.currentTarget);
李靖 authored
315
    if (!$this.hasClass('new-nav-home')) {
316 317 318 319 320 321
        $('.homebuttom').addClass('hide');
    } else {
        return false;
    }
});
李靖 authored
322
// 商品列表找相似按钮
李靖 authored
323
$('body').on('touchstart', '.similar-btn', function() {
李靖 authored
324 325 326 327 328 329 330
    let $thisP = $(this).parents('.good-info');

    $thisP.find('.similar-c').toggle();
    $thisP.siblings('.good-info').find('.similar-c').hide();
    return false;
});
毕凯 authored
331
(function() {
lijing authored
332
    let lastTime = 0,
毕凯 authored
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352
        prefixes = 'webkit moz ms o'.split(' '),
        requestAnimationFrame = window.requestAnimationFrame,
        cancelAnimationFrame = window.cancelAnimationFrame,
        prefix,
        i;

    // 通过遍历各浏览器前缀,来得到requestAnimationFrame和cancelAnimationFrame在当前浏览器的实现形式
    for (i = 0; i < prefixes.length; i++) {
        if (requestAnimationFrame && cancelAnimationFrame) {
            break;
        }
        prefix = prefixes[i];
        requestAnimationFrame = requestAnimationFrame || window[prefix + 'RequestAnimationFrame'];
        cancelAnimationFrame = cancelAnimationFrame || window[prefix + 'CancelAnimationFrame'] ||
            window[prefix + 'CancelRequestAnimationFrame'];
    }

    // 如果当前浏览器不支持requestAnimationFrame和cancelAnimationFrame,则会退到setTimeout
    if (!requestAnimationFrame || !cancelAnimationFrame) {
        requestAnimationFrame = function(callback) {
lijing authored
353
            let currTime = new Date().getTime();
毕凯 authored
354 355

            // 为了使setTimteout的尽可能的接近每秒60帧的效果
lijing authored
356 357
            let timeToCall = Math.max(0, 16 - (currTime - lastTime));
            let id = window.setTimeout(function() {
毕凯 authored
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
                callback(currTime + timeToCall);
            }, timeToCall);

            lastTime = currTime + timeToCall;
            return id;
        };

        cancelAnimationFrame = function(id) {
            window.clearTimeout(id);
        };
    }

    window.requestAnimationFrame = requestAnimationFrame;
    window.cancelAnimationFrame = cancelAnimationFrame;
}());


// 临时修改  footer
function phoneHidden(phone) {
    return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
}

if ($footer.find('.user-name').text().length === 11) {
    $footer.find('.user-name').html(phoneHidden($footer.find('.user-name').text()));
}
郝肖肖 authored
384
// 浮层下载APP
zhangxiaoru authored
385
function downLoadApp(unionType) {
lijing authored
386 387
    let appUrl = 'http://union.yoho.cn/union/downapp.html';
    let clickedAt = new Date();
郝肖肖 authored
388 389

    setTimeout(function() {
lijing authored
390
        let mkt = unionType || queryString().union_type || cookie('unionTypeYas') || false;
郝肖肖 authored
391 392 393 394 395 396 397 398 399

        if ((new Date()) - clickedAt < 2000) {
            if (mkt) {
                appUrl += '?union_type=' + mkt;
            }

            if (window._yas && window._yas.sendCustomInfo) {
                window._yas.sendCustomInfo({
                    op: 'YB_DOWNLOAD_C',
沈志敏 authored
400 401 402 403
                    param: JSON.stringify({
                        C_ID: _ChannelVary[cookie('_Channel')] || 1,
                        TO_URL: appUrl
                    })
郝肖肖 authored
404 405 406
                }, true);
            }
郝肖肖 authored
407
            window.location = appUrl;
郝肖肖 authored
408 409 410 411
        }
    }, 500);
}
郝肖肖 authored
412 413 414 415 416 417
// 为您优选埋点 http://redmine.yoho.cn/issues/10117
function givePoint(parameter) {
    if (!window._yas || !window._yas.sendCustomInfo) {
        return false;
    }
沈志敏 authored
418 419 420 421
    if (!parameter.REC_POSE || !parameter.PRD_ID) {
        return true;
    }
郝肖肖 authored
422
    // 男:1,女:2,潮童:3,创意生活:4
陈峰 authored
423 424
    let CID = _ChannelVary[cookie('_Channel')] || 1;
    let isAppOp = parameter.isAppOp;
郝肖肖 authored
425 426 427 428 429 430

    parameter = $.extend({
        REC_ID: RECID,
        PRD_NUM: 0,
        C_ID: CID,
        ACTION_ID: 0,
沈志敏 authored
431
        PAGE_NUM: 1
郝肖肖 authored
432
    }, parameter);
沈志敏 authored
433
    delete parameter.isAppOp;
郝肖肖 authored
434 435 436

    window._yas.sendCustomInfo({
        op: 'YB_CHOOSE_FOR_YOU_Y',
沈志敏 authored
437
        appop: isAppOp ? 'YB_CHOOSE_FOR_YOU' : '', // app内打开wap的埋点场合
郝肖肖 authored
438 439 440 441
        param: JSON.stringify(parameter)
    }, true);
}
郭成尧 authored
442 443 444
/**
 * 页面头颜色修正
 */
郭成尧 authored
445
(function() {
lijing authored
446 447 448
    let channel = cookie('_Channel');
    let header = $('#yoho-header, .homebuttom');
    let footer = $('.footer-tab .tab-item.current');
郭成尧 authored
449
陈峰 authored
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
    if (!header.hasClass('set-channel')) {
        if (!/^\/home/.test(location.pathname)) {
            switch (channel) {
                case 'boys':
                    if (!header.hasClass('boys')) {
                        header.addClass('boys');
                    }
                    break;
                case 'girls':
                    if (!header.hasClass('girls')) {
                        header.addClass('girls');
                    }
                    break;
                case 'lifestyle':
                    if (!header.hasClass('life-style')) {
                        header.addClass('life-style');
                    }
                    break;
                case 'kids':
                    if (!header.hasClass('kids')) {
                        header.addClass('kids');
                    }
                    break;
                default:
                    if (!header.hasClass('boys')) {
                        header.addClass('boys');
                    }
                    break;
            }
        } else {
陈峰 authored
480 481 482 483
            header.removeClass('kids');
            header.removeClass('girls');
            header.removeClass('life-style');
            header.addClass('boys');
484
        }
郭成尧 authored
485
    }
沈志敏 authored
486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513

    switch (channel) {
        case 'boys':
            if (footer) {
                footer.addClass('boys');
            }
            break;
        case 'girls':
            if (footer) {
                footer.addClass('girls');
            }
            break;
        case 'lifestyle':
            if (footer) {
                footer.addClass('life-style');
            }
            break;
        case 'kids':
            if (footer) {
                footer.addClass('kids');
            }
            break;
        default:
            if (footer) {
                footer.addClass('boys');
            }
            break;
    }
郭成尧 authored
514 515
}());
毕凯 authored
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
// 暴露公共接口
window.cookie = cookie;

window.setCookie = setCookie;

window.isCookiesEnabled = isCookiesEnabled;

window.getUser = getUser;

window.getUid = getUid;

window.getShoppingKey = getShoppingKey;

window.rePosFooter = rePosFooter;

window.reMarginFooter = reMarginFooter;
ccbikai authored
532 533

window.queryString = queryString();
郝肖肖 authored
534 535

window.givePoint = givePoint;
536 537

window._ChannelVary = _ChannelVary;
郝肖肖 authored
538 539

window.downLoadApp = downLoadApp;
陈峰 authored
540 541

window.mapSort = mapSort;
542 543

require('common/weixin-report');