define("index", ["jquery","hammer","swiper","lazyload","mlellipsis","iscroll-probe","handlebars","source-map","index"], function(require, exports, module){ var yohobuy; require("js/common"); require("js/category/entry"); require("js/guang/entry"); require("js/home/entry"); require("js/index/entry"); require("js/passport/entry"); require("js/product/entry"); require("js/me/entry"); module.exports = yohobuy; }); define("js/common", ["jquery"], function(require, exports, module){ /** * 页面公共逻辑 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/21 */ var $ = require("jquery"); var $footer = $('#yoho-footer'), $header = $('.yoho-header'); function cookie(name) { var cookies = document.cookie, cookieVal, offset; if (document.cookie && document.cookie !== '') { offset = cookies.indexOf(name + '='); if (offset > -1) { offset += name.length + 1; cookieVal = decodeURIComponent($.trim(cookies.substring(offset, cookies.indexOf(';', offset)))); } } return cookieVal; } function setCookie(name, value, options) { var expires = '', 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 getUser() { var c = cookie('_UID'), user; if (typeof c === 'undefined') { return 0; } user = c.split('::'); if (typeof user === 'undefined' || user.length < 4) { return 0; } return user; } function getUid() { var user = getUser(); if (user === 0) { return 0; } return user[1]; } function getShoppingKey() { var c = cookie('_g'); if (typeof c === 'undefined') { return ''; } return JSON.parse(c).k; } //根据页面内容重新设置通用底部的显示 function rePosFooter() { var winH; if ($footer.length === 0) { return; } winH = Math.min($(window).height(), window.screen.availHeight); if ($('body').height() <= winH - parseInt($footer.css('height'), 0)) { $footer.addClass('bottom'); } else { $footer.removeClass('bottom'); } } /** * * 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) { var fixedElH = $(fixedElement).outerHeight(); if (fixedElement) { $footer.css('margin-bottom', fixedElH + 'px'); } } //页面通用底部位置及status设置 (function() { var $op = $footer.children('.op-row'); var user = getUser(); rePosFooter(); //计算底部位置 if (user === 0) { //未登录 $op.prepend( '<a href="http://m.yohobuy.com/signin.html?refer=' + location.href + '">登录</a>' + '<span class="sep-line">|</span>' + '<a href="http://m.yohobuy.com/reg.html">注册</a>' ); } else { //已登录 $op.prepend( '<span>Hi,</span>' + '<a class="user-name" href="http://m.yohobuy.com/home?tmp=' + Math.random() + '">' + user[0] + '</a>' + '<a href="http://m.yohobuy.com/passport/signout/index?token=' + user[3] + '">退出</a>' ); } $op.find('.back-to-top').on('touchend', function() { $(window).scrollTop(0); return false; }); $footer.removeClass('hide'); }()); (function() { var uid = getUid(); uid = uid === 0 ? '' : uid; window._ozuid = uid;//暴露ozuid if (window._yas) { window._yas(1 * new Date(), '1.0.13.2', 'yohobuy_m', uid, ''); } }()); $header.on('touchstart', 'a', function() { $header.find('a').removeClass('highlight'); $(this).addClass('highlight'); }).on('touchend touchcancel', 'a', function() { $(this).removeClass('highlight'); }); (function() { var lastTime = 0, 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, element) { var currTime = new Date().getTime(); //为了使setTimteout的尽可能的接近每秒60帧的效果 var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; cancelAnimationFrame = function(id) { window.clearTimeout(id); }; } window.requestAnimationFrame = requestAnimationFrame; window.cancelAnimationFrame = cancelAnimationFrame; }()); //暴露公共接口 window.cookie = cookie; window.setCookie = setCookie; window.getUser = getUser; window.getUid = getUid; window.getShoppingKey = getShoppingKey; window.rePosFooter = rePosFooter; window.reMarginFooter = reMarginFooter; }); define("js/category/entry", ["jquery","hammer","swiper","lazyload","index"], function(require, exports, module){ /** * 品类打包入口 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/28 */ require("js/category/index"); require("js/category/brand"); }); define("js/category/index", ["jquery"], function(require, exports, module){ /** * 分类 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/14 */ var $ = require("jquery"); var $nav = $('.category-nav'), $categoryContainer = $('.category-container'), $contents = $categoryContainer.children('.content'), $subLevelItem = $categoryContainer.find('.sub-level li'), $primaryItem = $categoryContainer.find('.primary-level li'); var $curContent = $contents.not('.hide'); //初始化container高度 (function() { var $header = $('.yoho-header'), $search = $('#search-input'); var h = $(window).height() - $header.outerHeight() - $search.outerHeight() - $nav.outerHeight(); $categoryContainer.css('min-height', h); $contents.height(h); }()); $('#search-input').focus(function() { $(this).blur(); }); $nav.bind('contextmenu', function(e) { return false; }); $('.category-container').bind('contextmenu', function(e) { return false; }); $nav.on('touchend touchcancel', function(e) { var $this = $(e.target).closest('li'), index = $this.index(); if ($this.hasClass('focus')) { return; } $nav.find('li.focus').removeClass('focus'); $this.addClass('focus'); $curContent.addClass('hide'); $curContent = $contents.eq(index).removeClass('hide'); }); $categoryContainer.on('touchend', function(e) { var $this = $(e.target), $subLevel, $cur, index; $cur = $this.closest('.p-level-item'); if ($cur.length > 0) { index = $cur.index(); $subLevel = $this.closest('.content').find('.sub-level'); if ($this.hasClass('focus')) { return; } $this.closest('.primary-level').children('.focus').removeClass('focus'); $this.addClass('focus'); $subLevel.not('.hide').addClass('hide'); $subLevel.eq(index).removeClass('hide'); } }); $categoryContainer.find('.primary-level').on('touchstart touchend touchcancel', 'li', function() { $primaryItem.removeClass('highlight'); $(this).addClass('highlight'); }).on('touchend touchcancel', 'li', function() { $(this).removeClass('highlight'); }); $categoryContainer.find('.sub-level').on('touchstart', 'li', function() { $subLevelItem.removeClass('highlight'); $(this).addClass('highlight'); }).on('touchend touchcancel', 'li', function() { $(this).removeClass('highlight'); }); $nav.on('touchstart', 'li', function() { $nav.find('li').removeClass('bytouch'); $(this).addClass('bytouch'); }).on('touchend touchcancel', 'li', function() { $nav.find('li').removeClass('bytouch'); }); }); define("js/category/brand", ["jquery","hammer","swiper","lazyload","index"], function(require, exports, module){ /** * 品牌一览 * @author: liangzhifeng<zhifeng.liang@yoho.cn> * @date: 2015/10/23 */ var $ = require("jquery"), Hammer = require("hammer"), Swiper = require("swiper"), lazyLoad = require("lazyload"); var swiper, $fixTitleBar, $brandList = $('.brand-list'), $icon = $('.search-icon'), hotBrandsSwiper; var searchH = $('.newbrand-search').outerHeight(), headerH = $('.yoho-header').outerHeight(), brandSwipe = parseInt(searchH) + parseInt(headerH) - 1, minBrandListTop; var brandsData, $keyword, clearTextHammer; //热门品牌滑动 hotBrandsSwiper = new Swiper('.brands-swiper', { grabCursor: true, slidesPerView: 'auto', wrapperClass: 'brands-list', slideElement: 'li' }); swiper = new Swiper('.swiper-container', { lazyLoading: true, loop: true, autoplay: 3000, pagination: '.swiper-pagination .pagination-inner' }); lazyLoad($('img.lazy')); $('.yoho-header').css({ 'z-index': 2, position: 'fixed', top: 0 }); if ($('.banner-top').length > 0) { $('.hot-brands').css('padding-top', '0'); } $fixTitleBar = $('<div class="title-bar fixed-title-bar"><h2></h2></div>'); $fixTitleBar.css({ position: 'fixed', top: brandSwipe }).hide(); minBrandListTop = brandSwipe + $('.hot-brands').outerHeight() + $('.banner-top').outerHeight(); $brandList.last().append($fixTitleBar); function scrollHandler() { var scrTop = $(window).scrollTop(); if ($brandList.eq(0).offset().top < minBrandListTop) { $fixTitleBar.hide(); } $brandList.each(function() { var offTop = $(this).offset().top - brandSwipe; if (scrTop >= offTop) { $fixTitleBar.css({ display: 'block' }).find('h2').html($(this).find('.title-bar').text()); } }); } //srcoll to load more $(window).scroll(function() { window.requestAnimationFrame(scrollHandler); }); function changeBackground() { var $brandList = $('.brand-list').find('p'); $brandList.on('touchstart', function() { $brandList.css('background', '#fff'); $(this).css('background', '#eee'); }).on('touchend touchcancel', function() { $(this).css('background', '#fff'); }); } changeBackground(); function searchResult() { var keyword = ($keyword.val() + '').toLowerCase(); var result = {}, i = 0, html = ''; if (keyword !== '') { // 遍历首字母搜索 $.each(brandsData, function(k, v) { if ($.isArray(v)) { // 遍历品牌,进行匹配 $.each(v, function(i, brand) { if (brand.name.toLowerCase().indexOf(keyword) > -1) { result[k] = result[k] || []; result[k].push(brand); } }); } }); // 根据搜索结果生成 HTML $.each(result, function(k, v) { var brandHtml = ['<div class="brand-list bar-', i, '">']; i++; brandHtml.push('<div class="title-bar"><h2>'); brandHtml.push(k); brandHtml.push('</h2></div>'); $.each(v, function(i, brand) { brandHtml.push('<p><a href="' + brand.url + '">' + brand.name); if (brand.isNew) { brandHtml.push('<i class="icon-new">NEW</i>'); } if (brand.isHot) { brandHtml.push('<i class="icon-hot">HOT</i>'); } brandHtml.push('</a></p>'); }); brandHtml.push('</div>'); html += brandHtml.join(''); }); } // 插入 dom,绑定事件 $('.search-result').html(html); changeBackground(); } if ($('.brand-search-page').length) { brandsData = $.parseJSON($('#brands-data').html()); $keyword = $('#keyword'); $keyword.on('input', function() { if ($keyword.val().length) { $icon.css('color', '#000'); $(this).closest('.search-box').css('width', '11.25rem'); $('.search-action').show(); } else { $icon.css('color', '#b2b2b2'); $(this).closest('.search-box').css('width', '12.5rem'); $('.search-action').hide(); } searchResult(); }).focus(); clearTextHammer = new Hammer($('.clear-text')[0]); clearTextHammer.on('tap', function(e) { e.preventDefault(); $('.search-result').html(''); $('#keyword').val('').trigger('input'); e.srcEvent.stopPropagation(); }); $('form.search-box').on('submit', function() { return false; }); } }); define("js/guang/entry", ["jquery","lazyload","swiper","hammer","mlellipsis","iscroll-probe","index"], function(require, exports, module){ /** * 逛打包入口 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/9 */ require("js/guang/plus-star/list"); require("js/guang/plus-star/detail"); require("js/guang/home"); require("js/guang/list"); require("js/guang/detail"); }); define("js/guang/plus-star/list", ["jquery","lazyload","swiper","index"], function(require, exports, module){ /** * PLUS+STAR列表页 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/10 */ var $ = require("jquery"), lazyLoad = require("lazyload"), Swiper = require("swiper"); var $navs = $('#nav-tab > li'), $contents = $('#ps-content > .content'); var mySwiper; lazyLoad($('img.lazy')); mySwiper = new Swiper('.swiper-container', { lazyLoading: true, pagination: '.swiper-pagination' }); $('#nav-tab').bind('contextmenu', function(e) { return false; }); $('#nav-tab').on('touchend touchcancel', function(e) { var $this = $(e.target).closest('li'); if ($this.hasClass('focus')) { return; } $navs.toggleClass('focus'); $contents.toggleClass('hide'); $(document).trigger('scroll'); //Trigger lazyLoad }); $('#nav-tab').on('touchstart', function(e) { var target = e.target || e.srcElement; target.className = 'bytouch ' + target.className; }).on('touchend touchcancel', function() { $navs.removeClass('bytouch'); }); }); define("js/guang/plus-star/detail", ["jquery","hammer","mlellipsis","lazyload"], function(require, exports, module){ /** * PLUS+STAR详情页 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/10 */ var $ = require("jquery"), Hammer = require("hammer"), ellipsis = require("mlellipsis"), lazyLoad = require("lazyload"); var $intro = $('#intro'), $imt = $('#intro-more-txt'), $infosContainer = $('#related-infos-container'); var info = require("js/guang/info"); var tip = require("js/plugin/tip"); var brandId = $('#brand-info').data('id'); var jumpToApp = $('#jump-to-app').val(); var mIntro, aIntro; var moreHammer, likeHammer; require("js/plugin/wx-share"); ellipsis.init(); //Init LazyLoad lazyLoad($('img.lazy')); //文字介绍文字截取 $intro[0].mlellipsis(3); //获取截取文字和完整文字 setTimeout(function() { mIntro = $intro.text(); aIntro = $intro.attr('title'); }); info.initInfosEvt($infosContainer); //文字介绍收起与展开 moreHammer = new Hammer(document.getElementById('more-intro')); moreHammer.on('tap', function(e) { var $this = $(e.target).closest('#more-intro'); $this.toggleClass('spread'); if ($this.hasClass('spread')) { //显示 $intro.text(aIntro); $imt.text('收起'); } else { //隐藏 $intro.text(mIntro); $imt.text('more'); $(window).scrollTop(0, 400); //滑动到顶部 } e.preventDefault(); //防止收缩后误点到商品产生跳转 }); //品牌收藏 likeHammer = new Hammer(document.getElementById('brand-like')); likeHammer.on('tap', function(e) { var opt = 'ok', $this = $(e.target); //jumpToApp = 1表示APP未登录的情况,此时不发送ajax请求而由a链接直接跳转APP if (jumpToApp === '1') { return; } e.preventDefault(); if ($this.hasClass('like')) { opt = 'cancel'; } $.ajax({ type: 'POST', url: '/guang/opt/favoriteBrand', data: { id: brandId, opt: opt }, success: function(data) { if (data.code === 200) { $this.toggleClass('like'); } else if (data.code === 400 || data.code === 412) { location.href = data.data; //未登录跳转登录页面 } else { tip.show(data.message); } }, error: function() { tip.show('网络断开连接了~'); } }); }); }); define("js/guang/info", ["jquery","hammer","mlellipsis","lazyload"], function(require, exports, module){ /** * 资讯相关API * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/10 */ var $ = require("jquery"), Hammer = require("hammer"), ellipsis = require("mlellipsis"), lazyLoad = require("lazyload"); var tip = require("js/plugin/tip"); var loading = require("js/plugin/loading"); var $loadMoreInfo = $('#load-more-info'); var $loading = $(''), $noMore = $(''); var searching = false; ellipsis.init(); if ($loadMoreInfo.length > 0) { $loading = $loadMoreInfo.children('.loading'); $noMore = $loadMoreInfo.children('.no-more'); } /** * 设置指定资讯项的Lazyload和文字截取 * @params $infos 资讯项 */ function setLazyLoadAndMellipsis($infos) { lazyLoad($infos.find('img.lazy')); $infos.each(function() { var $this = $(this), $title = $this.find('.info-title'), $text = $this.find('.info-text'); $title[0].mlellipsis(2); $text[0].mlellipsis(2); }); } /** * 初始化资讯列表事件绑定 * @params $container 逛资讯列表容器 */ function initInfosEvt($container) { var cHammer; if (typeof $container === 'undefined') { return; } cHammer = new Hammer($container[0]); //点赞或者收藏事件 cHammer.on('tap', function(e) { var $this = $(e.target), opt = 'ok', $btn, $info; //e.preventDefault(); //点赞 $btn = $this.closest('.like-btn'); if ($btn.length > 0) { e.preventDefault(); if ($btn.hasClass('like')) { opt = 'cancel'; } $info = $this.closest('.guang-info'); $.ajax({ type: 'POST', url: '/guang/opt/praiseArticle', data: { id: $info.data('id'), opt: opt }, success: function(data) { var code = data.code; if (code === 200) { $btn.next('.like-count').text(data.data); //切换点赞状态 $btn.toggleClass('like'); } }, error: function() { tip.show('网络断开连接了~'); } }); return; } //APP收藏 $btn = $this.closest('.collect-btn'); if ($btn.length > 0) { e.preventDefault(); if ($btn.hasClass('collected')) { opt = 'cancel'; } $info = $this.closest('.guang-info'); $.ajax({ type: 'POST', url: '/guang/opt/collectArticle', data: { id: $info.data('id'), opt: opt }, success: function(data) { if (data.code && data.code === 200) { //切换收藏状态 $btn.toggleClass('collected'); } }, error: function() { tip.show('网络断开连接了~'); } }); } }); setLazyLoadAndMellipsis($container.find('.guang-info')); } /** * 资讯LoadMore * @param $container 资讯容器 jqyeryObject * @param opt 请求参数 * @param url[可选], 扩展请求的url而不使用默认值 */ function loadMore($container, opt, url) { var num; if (searching) { return; } if (opt.end) { return; } if (opt.page === 1) { //显示loading loading.showLoadingMask(); } num = $container.find('.guang-info').length; searching = true; $.ajax({ type: 'GET', url: url ? url : '/guang/index/page',//对于指定url的使用指定url(存在不同的控制器) data: opt, success: function(data) { var $newItems; if (data === ' ') { opt.end = true; searching = false; // $loading.addClass('hide'); $noMore.removeClass('hide'); return; } $container.append(data); if (num > 0) { $newItems = $container.find('.guang-info:gt(' + (num - 1) + ')'); } else { $newItems = $container.find('.guang-info'); } setLazyLoadAndMellipsis($newItems); if (opt.page === 1) { loading.hideLoadingMask(); $loading.removeClass('hide');//显示空屏加载时hide的隐藏 window.rePosFooter();//插入内容后重新计算底部位置 } opt.page++; searching = false; }, error: function() { tip.show('网络断开连接了~'); searching = false; } }); } exports.initInfosEvt = initInfosEvt; exports.setLazyLoadAndMellipsis = setLazyLoadAndMellipsis; exports.loadMore = loadMore; }); define("js/plugin/tip", ["jquery"], function(require, exports, module){ /** * 弹框提示 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/10 */ var $ = require("jquery"); var $tip, tipItime; /** * 初始化提示框 */ (function() { var tipHtml = '<div id="yoho-tip" class="yoho-tip"></div>'; //插入提示HTML $('.yoho-page').append(tipHtml); $tip = $('#yoho-tip'); $tip.on('touchend', function() { $tip.hide(); //清除Timeout clearTimeout(tipItime); }); }()); /** * 显示提示 */ function show(con, dur) { var content, duration; if (typeof con === 'undefined') { return; } content = con.toString(); duration = (dur && dur > 0) ? dur : 2000; $tip.text(content).show(); tipItime = setTimeout(function() { if ($tip.css('display') === 'block') { $tip.hide(); } }, duration); } exports.show = show; }); define("js/plugin/loading", ["jquery"], function(require, exports, module){ /** * Loading mask * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/29 */ var $ = require("jquery"); var $page = $('.yoho-page'); var $loading, hasInit = false; /** modify by liangzhifeng at 2015.11.2 */ // 初始化 function init($container) { var html = '<div class="loading-mask hide">' + '<div class="loading">' + '<div></div><div></div><div></div>' + '</div>' + '</div>'; hasInit = true; if ($container === undefined) { $container = $page; } $container.append(html); $loading = $container.children('.loading-mask'); } //显示loading function showLoadingMask() { if (!hasInit) { init(); hasInit = true; } $loading.removeClass('hide'); } //隐藏loading function hideLoadingMask() { $loading.addClass('hide'); } exports.init = init; exports.showLoadingMask = showLoadingMask; exports.hideLoadingMask = hideLoadingMask; }); define("js/plugin/wx-share", ["jquery"], function(require, exports, module){ /** * 微信分享 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/30 */ var $ = require("jquery"); module.exports = function() { var _weChatInterface = 'http://www.yohoshow.com/api/wechat/getSignPackage'; $.getJSON(_weChatInterface + '?pageurl=' + encodeURIComponent(location.href.split('#')[0]) + '&callback=?', function (json) { var _appId, _timestamp, _nonceStr, _signature; if (json !== undefined && json !== '') { _appId = json.appId.toString(); _timestamp = json.timestamp; _nonceStr = json.nonceStr.toString(); _signature = json.signature.toString(); wx.config({ debug: false, appId: _appId, timestamp: _timestamp, nonceStr: _nonceStr, signature: _signature, jsApiList: [ 'checkJsApi', 'onMenuShareTimeline', 'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'hideMenuItems', 'showMenuItems', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem', 'translateVoice', 'startRecord', 'stopRecord', 'onRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice', 'uploadVoice', 'downloadVoice', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'getNetworkType', 'openLocation', 'getLocation', 'hideOptionMenu', 'showOptionMenu', 'closeWindow', 'scanQRCode', 'chooseWXPay', 'openProductSpecificView', 'addCard', 'chooseCard', 'openCard' ] }); } }); wx.ready(function () { var shareTitle = $('#shareTitle').val(); var shareImg = $('#shareImg').val(); var shareDesc = $('#shareDesc').val(); var shareLink = $('#shareLink').val(); var shareData = { title: shareTitle, desc: shareDesc, imgUrl: shareImg, link: shareLink }; wx.onMenuShareAppMessage(shareData); wx.onMenuShareTimeline(shareData); wx.onMenuShareQQ(shareData); wx.onMenuShareWeibo(shareData); }); }; }); define("js/guang/home", ["jquery","swiper","hammer","mlellipsis","lazyload","index"], function(require, exports, module){ /** * 逛首页 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/10 */ var $ = require("jquery"), Swiper = require("swiper"); var info = require("js/guang/info"), loadMore = info.loadMore; var $loadMoreInfo = $('#load-more-info'); var $loading = $(''), $noMore = $(''); var winH = $(window).height(); var $infoList = $('#info-list'), $infos = $infoList.children('.info-list'), $nav = $('#guang-nav'), $curNav = $nav.children('.focus'), curType = $curNav.data('type'); var state = {}; var mySwiper; if ($loadMoreInfo.length > 0) { $loading = $loadMoreInfo.children('.loading'); $noMore = $loadMoreInfo.children('.no-more'); } mySwiper = new Swiper('.swiper-container', { lazyLoading: true, pagination: '.swiper-pagination', autoplay: 3000 }); info.initInfosEvt($infoList); //初始化各Nav下资讯加载的状态 (function() { var gender = $('#gender').val(); $nav.children('.guang-nav-item').each(function() { var type = $(this).data('type'), focus = $(this).hasClass('focus'); state[type] = { page: focus ? 2 : 1, gender: gender, type: type, end: false }; }); }()); $nav.bind('contextmenu', function(e) { return false; }); $nav.on('touchend touchcancel', function(e) { var $this = $(e.target).closest('.guang-nav-item'), $content, index; if ($this.hasClass('focus')) { return; } index = $this.index(); $this.addClass('focus'); $curNav.removeClass('focus'); $content = $infos.eq(index); $curNav = $this; curType = $this.data('type'); //当未加载数据时去请求数据 if (state[curType].page === 1) { //无数据时隐藏正在加载和没有更多字样 $loading.addClass('hide'); $noMore.addClass('hide'); loadMore($content, state[curType]); } else { //重置当前Tab的load-more if (state[curType].end) { $loading.addClass('hide'); $noMore.removeClass('hide'); } else { $loading.removeClass('hide'); $noMore.addClass('hide'); } } $infos.not('.hide').addClass('hide'); $content.removeClass('hide'); if (state[curType].page === 1) { window.rePosFooter();//进入空内容时重新定位footer位置 } }); function scrollHandler() { var $c = $infos.not('.hide'); if ($(window).scrollTop() + winH >= $(document).height() - 0.25 * $c.height()) { loadMore($c, state[curType]); } } //srcoll to load more $(document).scroll(function() { window.requestAnimationFrame(scrollHandler); }); $nav.on('touchstart', function(e) { var target = e.target || e.srcElement; target.className = 'bytouch ' + target.className; }).on('touchend touchcancel', function() { $nav.find('li').removeClass('bytouch'); }); }); define("js/guang/list", ["jquery","hammer","mlellipsis","lazyload"], function(require, exports, module){ /** * 列表页,编辑页 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/10 */ var $ = require("jquery"); var info = require("js/guang/info"), loadMore = info.loadMore; var winH = $(window).height(); var $author = $('#author-infos'); var $tag = $('#tag'); var $gender = $('#gender'); var $isApp = $('#isApp'); var setting = { page: 2, end: false }; var $infos = $('#info-list'); info.initInfosEvt($infos); if ($author.length > 0) { $.extend(setting, { authorId: $author.data('id'), isApp: $isApp.val() }); } if ($tag.length > 0) { $.extend(setting, { tag: $tag.val(), gender: $gender.val(), isApp: $isApp.val() }); } function scrollHandler() { if ($(window).scrollTop() + winH >= $(document).height() - 0.25 * $infos.height()) { loadMore($infos, setting); } } //srcoll to load more $(window).scroll(function() { window.requestAnimationFrame(scrollHandler); }); }); define("js/guang/detail", ["jquery","mlellipsis","lazyload","iscroll-probe"], function(require, exports, module){ /** * 逛详情页 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/13 */ var $ = require("jquery"), ellipsis = require("mlellipsis"), lazyLoad = require("lazyload"), IScroll = require("iscroll-probe"); var $authorIntro = $('.author .intro'); var pageInIscroll = false; var hasCollocationBlock = $('.collocation-block').length > 0 ? true : false; //collocation block variable var thumbWidth = 0, $fixedThumbContainer = $(''), $coBlock, $thumbContainer, $thumbs, $prods, scrollToEl; var scrollToEl = document.querySelector('#wrapper .collocation-block'); var winW = $(window).width(); var myScroll; require("js/plugin/wx-share")(); /** * 计算搭配的箭头的位置 * @param $curPos 当前focus的搭配项 */ function posCollocationArrow($curCo) { var left = $curCo.offset().left, bgPos = -winW + left + (thumbWidth / 2) + 'px'; $thumbContainer.css({ backgroundPosition: bgPos + ' bottom' }); if (pageInIscroll) { $fixedThumbContainer.css({ backgroundPosition: bgPos + ' bottom' }); } } //搭配thumb的touch事件句柄 function thumbTouchEvt(e) { var $curCo = $(e.currentTarget), index = $curCo.index(), $brother, $brotherCo, $curProds; if ($curCo.hasClass('focus')) { return; } $thumbs.filter('.focus').removeClass('focus'); if (pageInIscroll) { if ($curCo.closest('.fixed-thumb-container').length > 0) { $brother = $thumbContainer; } else { $brother = $fixedThumbContainer; } $brotherCo = $brother.find('.thumb').eq(index); $fixedThumbContainer.find('.thumb.focus').removeClass('focus'); $brotherCo.addClass('focus'); } $curCo.addClass('focus'); //定位arrow posCollocationArrow($curCo); $prods.not('.hide').addClass('hide'); $curProds = $prods.eq(index); $curProds.removeClass('hide'); // lazyLoad($curProds.find('.lazy')); if (pageInIscroll) { if (myScroll) { myScroll.scrollToElement(scrollToEl, 400); } } else { $('body').animate({ scrollTop: $coBlock.offset().top }, 400); } myScroll && myScroll.refresh(); } // 初始化iscroll function initIscroll() { var $scroller = $('#scroller'), $yohoHeader = $('.yoho-header'); var hH = 0, winH, tcH, cbH, cbTop, fixedThumbDom; //考虑通用头部的影响:对offset().top以及winH做对应偏移 if ($yohoHeader.length > 0) { hH = $yohoHeader.outerHeight(); } myScroll = new IScroll('#wrapper', { probeType: 3, mouseWheel: true, click: true }); document.addEventListener('touchmove', function(e) { e.preventDefault(); }, false); if (!hasCollocationBlock) { myScroll.on('scroll', function() { $scroller.trigger('scroll'); }); return; } winH = $(window).height() - hH; fixedThumbDom = $fixedThumbContainer[0]; tcH = $thumbContainer.outerHeight(); cbH = $coBlock.outerHeight(); cbTop = $coBlock.offset().top - hH; myScroll.on('scroll', function() { var sTop = -this.y; var classList = fixedThumbDom.className; if (sTop <= cbTop - winH + tcH) { if (classList.indexOf('fixed-bottom') === -1) { $fixedThumbContainer .addClass('fixed-bottom') .removeClass('hide'); } } else if (sTop <= cbTop) { if (classList.indexOf('hide') === -1) { $fixedThumbContainer .addClass('hide') .removeClass('fixed-bottom fixed-top'); } } else if (sTop <= cbTop + cbH - tcH) { if (classList.indexOf('fixed-top') === -1) { $fixedThumbContainer .addClass('fixed-top') .removeClass('hide absolute') .css('top', ''); } } else if (sTop <= cbTop + cbH) { if (classList.indexOf('absolute') === -1) { $fixedThumbContainer .addClass('absolute') .removeClass('fixed-top hide'); } fixedThumbDom.style.top = cbTop + hH + cbH - tcH - sTop + 'px'; } else if (sTop > cbTop + cbH) { if (classList.indexOf('hide') === -1) { $fixedThumbContainer .addClass('hide') .removeClass('absolute'); } } $scroller.trigger('scroll'); }); } //window onload 后重新refresh iscroll window.onload = function() { myScroll && myScroll.refresh(); }; //初始化页面,包括是否使用iscorll初始化页面 //接口暴露在HTML中,使用压缩名 exports.i = function(useIscroll) { var isIphone = navigator.userAgent.indexOf('iPhone') > 0 ? true : false; pageInIscroll = isIphone && useIscroll; ellipsis.init(); lazyLoad($('.lazy')); //title mlellipsis $('.info-list .title, .one-good .reco-name').each(function() { this.mlellipsis(2); }); //offset.left约等于marginLeft的值则表示介绍被换行,则清除intro的paddingTop让其更靠近头像和作者名 if ($authorIntro.offset() && (parseInt($authorIntro.offset().left, 10) === parseInt($authorIntro.css('margin-left'), 10))) { $authorIntro.css('padding-top', 0); } if (pageInIscroll) { if ($('.yoho-header').length > 0) { $('#wrapper').addClass('ios has-head'); } else { $('#wrapper').addClass('ios'); } } //有搭配模块,iphone使用iscroll初始化滚动并有固定的搭配栏,其他的没有 if (hasCollocationBlock) { $coBlock = $('.collocation-block'); $thumbContainer = $coBlock.children('.thumb-container'); $thumbs = $thumbContainer.find('li'); $prods = $coBlock.find('.prod'); thumbWidth = $thumbs.width(); if (pageInIscroll) { $fixedThumbContainer = $('#wrapper') .after($thumbContainer.clone().addClass('fixed-thumb-container fixed-bottom')) .next('.thumb-container'); //load img of fixed thumb container lazyLoad($fixedThumbContainer.find('.lazy'), { event: 'sporty' }); } //Init Arrow Position posCollocationArrow($thumbs.filter('.focus')); $thumbContainer.delegate('.thumb', 'touchend', thumbTouchEvt); if (pageInIscroll) { $fixedThumbContainer.delegate('.thumb', 'touchend', thumbTouchEvt); } } if (pageInIscroll) { initIscroll(); } }; }); define("js/home/entry", ["jquery","hammer","swiper","lazyload","index"], function(require, exports, module){ /** * 首页打包入口 * @author: liangzhifeng<zhifeng.liang@yoho.cn> * @date: 2015/10/12 */ require("js/home/home"); require("js/home/maybe-like"); }); define("js/home/home", ["jquery","hammer","swiper","lazyload","index"], function(require, exports, module){ /** * 首页 * @author: liangzhifeng<zhifeng.liang@yoho.cn> * @date: 2015/10/12 */ var $ = require("jquery"), Hammer = require("hammer"), Swiper = require("swiper"), lazyLoad = require("lazyload"), $mobileWrap = $('.mobile-wrap'), $overlay = $('.overlay'), $sideNav = $('.side-nav'), $subNav = $('.sub-nav'), bannerSwiper, recommendSwiper, hotBrandsSwiper, trendTopicSwiper, goodsSwiper; var requestFrame, thisFunc, start = 0, i, swiperClass, supportCss3, $logotrans = $('.home-header .logo'), isen = true; var navHammer; require("js/home/maybe-like"); lazyLoad($('img.lazy')); navHammer = new Hammer($('.nav-btn')[0]); navHammer.on('tap', function(event) { event.preventDefault(); $mobileWrap.addClass('menu-open'); $overlay.show().css('opacity', 0.3); $sideNav.addClass('on'); //设置boy高宽,页面不能上下滑动 $('body').css({ height: $(window).height(), width: $(window).width(), overflow: 'hidden' }); event.srcEvent.stopPropagation(); return false; }); function hideSideBar() { if ($mobileWrap.hasClass('menu-open')) { $mobileWrap.removeClass('menu-open'); $('.overlay').hide(); $('.sub-nav').removeClass('show'); $sideNav.removeClass('on'); $('body').css({ height: 'auto', overflow: 'auto' }); } } $('.overlay').on('touchstart', function(e) { hideSideBar(); return false; }); //点击一级导航,弹出二级导航 $sideNav.on('touchstart', 'li', function(e) { if ($(this).find('.sub-nav').size() > 0) { $('.sub-nav').removeClass('show'); $(this).find('.sub-nav').addClass('show'); } e.stopPropagation(); if (e.target.pathname === location.pathname) { hideSideBar(); return false; } }); //返回一级导航,收起二级导航 $subNav.each(function() { $(this).find('li').eq(0).on('touchstart', function(e) { $('.sub-nav').removeClass('show'); e.stopPropagation(); return false; }); }).on('touchstart', function(e) { if (e.currentTarget !== e.target) { $subNav.find('li').removeClass('current'); } }); // 侧边栏点击背景色变化 $sideNav.children('ul').children('li').on('touchstart', function() { $sideNav.children('ul').children('li').css('background', '#fff'); $(this).css('background', '#eee'); }).on('touchend touchcancel', function() { $(this).css('background', '#fff'); }); //头部banner轮播 if ($('.banner-swiper').find('li').size() > 1) { bannerSwiper = new Swiper('.banner-swiper', { lazyLoading: true, lazyLoadingInPrevNext: true, loop: true, autoplay: 3000, autoplayDisableOnInteraction: false, paginationClickable: true, slideElement: 'li', pagination: '.banner-top .pagination-inner' }); } //热门品牌滑动 hotBrandsSwiper = new Swiper('.brands-swiper', { grabCursor: true, slidesPerView: 'auto', wrapperClass: 'brands-list', slideElement: 'li' }); //推荐搭配滑动 recommendSwiper = new Swiper('.recommend-swiper', { grabCursor: true, slidesPerView: 'auto', wrapperClass: 'recommend-list', slideElement: 'li' }); //潮品话题轮播 if ($('.trend-topic-swiper').find('li').size() > 1) { trendTopicSwiper = new Swiper('.trend-topic-swiper', { loop: true, autoplay: 3000, autoplayDisableOnInteraction: false, paginationClickable: true, slideElement: 'li', pagination: '.trend-topic-content .pagination-inner' }); } //潮流上装/经典裤装等轮播 $('.category-swiper').each(function(i, index) { swiperClass = 'category-swiper' + i; $(this).addClass(swiperClass); if ($('.' + swiperClass).find('.swiper-slide').size() > 1) { goodsSwiper = new Swiper('.' + swiperClass, { loop: true, autoplay: 3000, autoplayDisableOnInteraction: false, paginationClickable: true, slideElement: 'li', pagination: '.' + swiperClass + ' .pagination-inner' }); } }); //logo动画 requestFrame = (function() { var tempFunc = null, prefixList = ['webkit', 'moz', 'ms']; for (i = 0; i < prefixList.length; i++) { thisFunc = prefixList[i] + 'RequestAnimationFrame'; if (window[thisFunc]) { supportCss3 = true; tempFunc = thisFunc; } } if (supportCss3) { return function(callback) { window[tempFunc](callback); }; } return function(callback) { window.setTimeout(callback, 67); }; })(); function tsAnimate() { start = start + 10; $logotrans.css({ transform: 'rotateX(' + start + 'deg)', '-webkit-transform': 'rotateX(' + start + 'deg)', '-moz-transform': 'rotateX(' + start + 'deg)' }); if (start / 90 % 2 === 1) { if (isen) { $logotrans.addClass('animate'); isen = false; } else { $logotrans.removeClass('animate'); isen = true; } } if (start / 90 % 2 === 0 && start % 360 !== 0) { window.setTimeout(tsAnimate, 3000); } else { if (start % 360 === 0) { window.setTimeout(tsAnimate, 60 * 1000); } else { requestFrame(function() { tsAnimate(); }); } } } setTimeout(tsAnimate, 3000); $('.home-header .iconfont').on('touchstart', function() { $(this).addClass('highlight'); }).on('touchend touchcancel', function() { $(this).removeClass('highlight'); }); // 底部留出tab 的高度 window.reMarginFooter('.footer-tab'); //set cookie exports.set = function(c) { window.setCookie('_Channel', c, { expires: 365, domain: '.m.yohobuy.com' }); }; }); define("js/home/maybe-like", ["jquery","hammer","lazyload"], function(require, exports, module){ /** * “你可能喜欢”模块JS * @author: liangzhifeng<zhifeng.liang@yoho.cn> * @date: 2015/10/12 */ var $ = require("jquery"), Hammer = require("hammer"), tip = require("js/plugin/tip"), loading = require("js/plugin/loading"), lazyLoad = require("lazyload"); var navHammer, winH = $(window).height(), $goodList = $('#goods-list'), searching = false, page = 0, gender = null, kidsType = $('.mobile-wrap').hasClass('kids-wrap') ? true : false, lifestyleType = $('.mobile-wrap').hasClass('lifestyle-wrap') ? true : false, num, url; var $curNav, index, $navList = $('#maybe-like-nav'); //ajax url if (kidsType) { url = '/product/recom/maylikekids'; } else if (lifestyleType) { url = '/product/recom/maylikelife'; } else { gender = $('.mobile-wrap').hasClass('boys-wrap') ? '1,3' : '2,3', url = '/product/recom/maylike?gender=' + gender; } $curNav = $navList.children('.focus'); if (lifestyleType) { navHammer = new Hammer($navList[0]); navHammer.on('tap', function(e) { var $this = $(e.target).closest('li'), $goods = $('.goods-list'), $content; e.preventDefault(); if ($this.hasClass('focus')) { return; } index = $this.index(); $this.addClass('focus'); $curNav.removeClass('focus'); $goods.not('.hide').addClass('hide'); $content = $goods.eq(index); $content.removeClass('hide'); $curNav = $this; $(document).trigger('scroll'); //Trigger lazyLoad e.srcEvent.stopPropagation(); }); } loading.init($('.maybe-like')); function search() { if (searching) { return; } searching = true; loading.showLoadingMask(); //num = $goodList.find('.good-info').length; $.ajax({ type: 'GET', url: url, data: { page: page + 1 }, success: function(data) { if (data === ' ') { searching = false; loading.hideLoadingMask(); if (gender) { if (gender === '1,3') { url = '/boys/bottomBanner'; } else { url = '/girls/bottomBanner'; } $.ajax({ type: 'GET', url: url, success: function(data) { if (data && data.img) { $('#load-more-img').show(); $('#load-more-img a').attr('href', data.url); $('#load-more-img a > img').attr('src', data.img); } }, error: function() { } }); } return; } num = $goodList.find('.good-info').length; $goodList.append(data); // 2015/10/31 fei.hong: 修复第一页分页不显示图片的问题 if (num === 0) { lazyLoad($goodList.find('.good-info').find('img.lazy')); } else { lazyLoad($goodList.find('.good-info:gt(' + (num - 1) + ')').find('img.lazy')); } searching = false; loading.hideLoadingMask(); page++; }, error: function() { tip.show('网络断开连接了~'); searching = false; loading.hideLoadingMask(); } }); } $('.maybe-like p').on('touchstart', function(e) { search(); }); function scrollHandler() { if ($(window).scrollTop() + winH >= $(document).height() - 200) { search(); } } //srcoll to load more $(window).scroll(function() { window.requestAnimationFrame(scrollHandler); }); }); define("js/index/entry", ["jquery","hammer"], function(require, exports, module){ /** * Index打包入口 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/19 */ require("js/index/search"); require("js/index/footer"); require("js/index/channel"); }); define("js/index/search", ["jquery","hammer"], function(require, exports, module){ /** * 搜索JS * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/19 */ var $ = require("jquery"), security = require("js/plugin/security"), Hammer = require("hammer"); var $input = $('#search-input input'); var $clear = $('#search-input .clear-input'); var $icon = $('.search-icon'); var $form = $('#search-form'); var $history = $('.history'); var $historySearch = $('.history-search'); var $clearHistory = $('#clear-history'); var writeSearch = require("js/index/write-search"); var ranToken = writeSearch.getRanToken(); var chHammer, cHammer; chHammer = new Hammer($clearHistory[0]); chHammer.on('tap', function() { localStorage.removeItem('historys'); $history.html(''); $historySearch.hide(); $clearHistory.hide(); window.rePosFooter(); }); $input.on('input', function() { if ($input.val() === '') { $icon.css('color', '#b2b2b2'); $clear.addClass('hide'); } else { $icon.css('color', '#666'); $clear.removeClass('hide'); } }); cHammer = new Hammer($clear[0]); cHammer.on('tap', function() { $input.val('').trigger('input'); }); $('#search').on('touchend', function() { if (security.hasDangerInput()) { return false; } $(this).closest('form').submit(); return false; }); //初始化历史搜索的内容 (function() { var html = '', history, historys, i; if (localStorage) { historys = localStorage.getItem('historys'); if (historys && historys.length > 0) { historys = historys.split(ranToken); for (i = historys.length; i > 0; i--) { history = historys[i - 1]; if (history === '') { continue; } html += '<li><a href="/?query=' + history + '">' + history + '</li>'; } $history.html(html); $clearHistory.removeClass('hide'); $historySearch.removeClass('hide'); window.rePosFooter(); } } }()); writeSearch.bindWirteLocal($form); }); define("js/plugin/security", ["jquery"], function(require, exports, module){ /** * 校验input, 防止SQL注入 * @author: 赵彪<bill.zhao@yoho.cn> * @date: 2015/11/30 */ var $ = require("jquery"), tip = require("js/plugin/tip"); /** * hasStrangeInput() return true when input have danger value * * @param {Bool} needConvert Set if the danger input value should be converted to space * @return {Bool} true/false If the input have danger value */ function hasDangerInput(needConvert) { var $inputs = $('input[type!=hidden], textarea'); var validationPartten = /['"<>&\|]|--/g, inputsLength = $inputs.length, val, i, matchChars, // to set if the input value should be coverted, and its default value is true; willConvert = needConvert === undefined || typeof needConvert !== 'boolean' ? true : needConvert; for (i = 0; i < inputsLength; i++) { val = $inputs.eq(i).val(); if (validationPartten.test(val)) { if (willConvert) { $inputs.eq(i).val(val.replace(validationPartten, ' ')); } else { matchChars = val.match(validationPartten).join(' '); tip.show('不可以输入 ' + matchChars + ' 哦!'); } return !willConvert && true; } } return false; } exports.hasDangerInput = hasDangerInput; }); define("js/index/write-search", [], function(require, exports, module){ /** * 将搜索结果存localStorage * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/29 */ var ranToken = ' ??++ '; //获取分隔符 function getRanToken() { return ranToken; } //绑定提交前的存local操作 function bindWirteLocal($form) { $form.on('submit', function() { var query = this.query.value, historys; if (localStorage) { historys = localStorage.getItem('historys'); historys = historys ? historys : ''; if (historys.indexOf(ranToken + query + ranToken) > -1) { return; } if (historys === '') { query = ranToken + query; } historys += query + ranToken; localStorage.setItem('historys', historys); } }); } exports.getRanToken = getRanToken; exports.bindWirteLocal = bindWirteLocal; }); define("js/index/footer", ["jquery","hammer"], function(require, exports, module){ /** * 底部JS * @author: liangzhifeng<zhifeng.liang@yoho.cn> * @date: 2015/10/26 */ var $ = require("jquery"), Hammer = require("hammer"); var floatLayerBtnHammer; require("js/common"); function downLoadApp() { var appUrl = 'http://a.app.qq.com/o/simple.jsp?pkgname=com.yoho&g_f=995445'; var clickedAt = new Date(); setTimeout(function () { if ((new Date()) - clickedAt < 2000) { window.location = appUrl; } }, 500); } $('#float-layer-close').on('touchend', function(e) { $('#float-layer-app').hide(); window.setCookie('_float-layer-app', 'id490655927', { domain: '.yohobuy.com' }); window.setCookie('_float-layer-app-close', 1, { domain: '.yohobuy.com', expires: 1 }); return false; }); if ($('#float-layer-btn') && $('#float-layer-btn')[0]) { floatLayerBtnHammer = new Hammer($('#float-layer-btn')[0]); floatLayerBtnHammer.on('tap', function(e) { downLoadApp('bottom'); e.srcEvent.stopPropagation(); }); if (typeof window.cookie === 'function' && !window.cookie('_float-layer-app')) { $('#float-layer-app').show(); } else { $('#float-layer-app').hide(); } } }); define("js/index/channel", ["jquery"], function(require, exports, module){ /** * 频道选择页面顶部搜索 * @author: bikai<kai.bi@yoho.cn> * @date: 2015/10/28 */ var $ = require("jquery"), security = require("js/plugin/security"); var $searchBox = $('.search-box'), $box = $('.box'), $indexSearch = $('.index-search'), $indexLogo = $('.index-logo'), $channelLink = $('.index-channel a'); var $search = $searchBox.children('input[type="text"]'), $cancelSearch = $box.children('.no-search'), $searchIcon = $searchBox.children('.search-icon'); require("js/common"); $search.on('focus', function() { $box.addClass('action'); $indexLogo.addClass('action'); }).on('input', function() { if ($search.val() === '') { $searchIcon.addClass('empty'); } else { $searchIcon.removeClass('empty'); } }); $cancelSearch.on('touchend', function() { $box.removeClass('action'); $indexLogo.removeClass('action'); $search.blur(); return false; }); $searchBox.children('.clear-text').on('touchstart', function() { $search.val('').focus().trigger('input'); }); $searchBox.children('.search-icon').on('touchstart', function() { if (security.hasDangerInput()) { return false; } $indexSearch.submit(); }); $searchBox.keyup(function(e) { if (e.keyCode === 13) { if (security.hasDangerInput()) { return false; } $indexSearch.submit(); } }); $('.index-channel img').on('load error', function() { window.rePosFooter && window.rePosFooter(); }); $channelLink.on('touchstart', function() { $channelLink.css({ background: '#000', color: '#fff', borderColor: '#fff' }); $(this).css({ background: 'rgba(255, 255, 255, 0.5)', color: '#000', borderColor: '#000' }); }).on('touchend touchcancel', function() { $(this).css({ background: '#000', color: '#fff', borderColor: '#fff' }); }); }); define("js/passport/entry", ["jquery"], function(require, exports, module){ /** * 注册、登录、密码找回打包入口 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/8 */ //注册 require("js/passport/register/register"); require("js/passport/register/code"); require("js/passport/register/password"); //登录 require("js/passport/login/login"); require("js/passport/login/international"); //密码找回 require("js/passport/back/mobile"); require("js/passport/back/code"); require("js/passport/back/email"); require("js/passport/back/email-success"); require("js/passport/back/new-password"); }); define("js/passport/register/register", ["jquery"], function(require, exports, module){ /** * 注册 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/8 */ var $ = require("jquery"); var $phoneNum = $('#phone-num'), $countrySelect = $('#country-select'), $areaCode = $('#area-code'), $btnNext = $('#btn-next'); var api = require("js/passport/api"); var tip = require("js/plugin/tip"); var trim = $.trim; var showErrTip = tip.show; api.selectCssHack($('#country-select')); api.bindClearEvt(); $phoneNum.bind('input', function() { if (trim($phoneNum.val()) === '') { $btnNext.addClass('disable'); } else { $btnNext.removeClass('disable'); } }); $countrySelect.change(function() { $areaCode.text($countrySelect.val()); }); $btnNext.on('touchstart', function() { var pn = trim($phoneNum.val()), areaCode = $countrySelect.val(); if ($btnNext.hasClass('disable')) { return; } if (api.phoneRegx[areaCode].test(pn)) { $.ajax({ url: '/passport/reg/verifymobile', type: 'POST', data: { areaCode: areaCode.replace('+', ''), phoneNum: pn }, success: function(data) { if (data.code === 200) { location.href = data.data; } else { showErrTip(data.message); } } }); } else { showErrTip('手机号格式不正确,请重新输入'); } }); }); define("js/passport/api", ["jquery"], function(require, exports, module){ /** * 登录注册公用API * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/8 */ var $ = require("jquery"); var trim = $.trim; //邮箱验证规则 var emailRegx = /^([a-zA-Z0-9]+[_|\_|\.|-]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.|-]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/; //手机号码验证规则 var phoneRegx = { '+86': /^1[35847]{1}[0-9]{9}$/, '+852': /^[965]{1}[0-9]{7}$/, '+853': /^[0-9]{8}$/, '+886': /^[0-9]{10}$/, '+65': /^[98]{1}[0-9]{7}$/, '+60': /^1[1234679]{1}[0-9]{8}$/, '+1': /^[0-9]{10}$/, '+82': /^01[0-9]{9}$/, '+44': /^7[789][0-9]{8}$/, '+81': /^0[9|8|7][0-9]{9}$/, '+61': /^[0-9]{11}$/ }; /** * 密码显示隐藏 * @params opt 初始化参数 */ function bindEyesEvt(opt) { var $hasEye = $('.has-eye'), $eye; if (opt && opt.status === 'open') { $hasEye.append('<div class="eye"></div>'); } else { $hasEye.append('<div class="eye close"></div>'); } $eye = $hasEye.children('.eye'); $eye.on('touchstart', function(e) { var $this = $(this), $pwd = $this.siblings('.pwd'); e.preventDefault(); $this.toggleClass('close'); //切换密码显示和文本显示 if ($this.hasClass('close')) { $pwd.attr('type', 'password'); } else { $pwd.attr('type', 'text'); } $pwd.focus(); }); } // 清空账号显示 function bindClearEvt() { var $hasClear = $('.has-clear'), $clear; $hasClear.append('<div class="clear-input"></div>'); $clear = $hasClear.children('.clear-input'); $clear.on('touchstart', function(e) { var $input = $clear.siblings('.input'); $input.val('').trigger('input').focus(); e.preventDefault(); }); //反向逻辑 $hasClear.children('.input').bind('input', function() { var $this = $(this), $thisClear = $this.siblings('.clear-input'), val = trim($this.val()); if (val === '') { $thisClear.hide(); } else { $thisClear.show(); } }); } // 密码长度验证 function pwdValidate(pwd) { if (pwd.length >= 6 && pwd.length <= 20) { return true; } return false; } // hack for resolving direction:rtl didn't work in android uc function selectCssHack($countrySelect) { var u = navigator.userAgent; function autoSelectWidth() { var wordCount = $countrySelect.find('option:selected').text().length; switch (wordCount) { //分别有2,3,4个汉字的情况 case 2: $countrySelect.outerWidth(90); break; case 3: $countrySelect.outerWidth(110); break; default: $countrySelect.outerWidth(130); } } if (u.match(/uc/i) && u.match(/android/i)) { $countrySelect.change(function() { autoSelectWidth(); }); } else { $countrySelect.removeClass('in-android-uc'); } } //Exports APIs module.exports = { emailRegx: emailRegx, phoneRegx: phoneRegx, bindEyesEvt: bindEyesEvt, bindClearEvt: bindClearEvt, pwdValidate: pwdValidate, selectCssHack: selectCssHack }; }); define("js/passport/register/code", ["jquery"], function(require, exports, module){ /** * 注册-验证码 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/8 */ require("js/passport/code")(true); }); define("js/passport/code", ["jquery"], function(require, exports, module){ /** * 注册/找回密码-验证码 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/8 */ var $ = require("jquery"); module.exports = function(useInRegister) { var $captcha = $('#captcha'), $btnNext = $('#btn-next'), $captchaTip = $('#captcha-tip'), phoneNum = $('#phone-num').val(), areaCode = $('#area-code').val().replace('+', ''); var api = require("js/passport/api"); var tip = require("js/plugin/tip"); var trim = $.trim; var showErrTip = tip.show; var urlMid = useInRegister ? 'reg' : 'back'; function countDown() { var count = 59, itime; itime = setInterval(function() { if (count === 0) { $captchaTip.text('重发验证码').removeClass('disable'); clearInterval(itime); } else { $captchaTip.text('重发验证码 (' + count-- + '秒)'); } }, 1000); } api.bindClearEvt(); $captcha.bind('input', function() { if (trim($captcha.val()) !== '') { $btnNext.removeClass('disable'); } else { $btnNext.addClass('disable'); } }); //重新发送验证码 $captchaTip.on('touchstart', function() { if ($captchaTip.hasClass('disable')) { return; } $.ajax({ type: 'POST', url: '/passport/' + urlMid + '/sendcode', data: { phoneNum: phoneNum, areaCode: areaCode }, success: function(data) { if (data.code === 200) { $captchaTip.text('重发验证码 (60秒)').addClass('disable'); countDown(); } else { //验证码不正确,显示提示 showErrTip(data.message); } } }); }); $btnNext.on('touchstart', function() { if ($btnNext.hasClass('disable')) { return; } $.ajax({ type: 'POST', url: '/passport/' + urlMid + '/verifycode', data: { phoneNum: phoneNum, areaCode: areaCode, code: trim($captcha.val()), token: $('#token').val() }, success: function(data) { if (data.code === 200) { location.href = data.data; } else { //验证码不正确,显示提示 showErrTip(data.message); } } }); }); countDown(); }; }); define("js/passport/register/password", ["jquery"], function(require, exports, module){ /** * 注册-密码 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/8 */ var $ = require("jquery"); var $pwd = $('#pwd'), $btnSure = $('#btn-sure'); var api = require("js/passport/api"); var tip = require("js/plugin/tip"); var trim = $.trim; var showErrTip = tip.show; api.bindEyesEvt({ status: 'open' //默认眼睛打开 }); $pwd.bind('input', function() { if (trim($pwd.val()) === '') { $btnSure.addClass('disable'); } else { $btnSure.removeClass('disable'); } }); $btnSure.on('touchstart', function() { var pwd = trim($pwd.val()); if ($btnSure.hasClass('disable')) { return; } if (api.pwdValidate(pwd) === false) { showErrTip('密码6-20位,请重新输入'); } else { $.ajax({ type: 'POST', url: '/passport/reg/setpassword', data: { password: pwd, phoneNum: $('#phone-num').val(), areaCode: $('#area-code').val(), token: $('#token').val() }, success: function(data) { var res; if (data.code === 200) { res = data.data; showErrTip('注册成功'); $.ajax({ url: res.session, dataType: 'jsonp' }); //1000ms后跳转页面 setTimeout(function() { location.href = res.href; }, 1000); } else { showErrTip(data.message); } } }); } }); }); define("js/passport/login/login", ["jquery"], function(require, exports, module){ /** * 登录 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/9/30 */ var $ = require("jquery"); var $account = $('#account'), $pwd = $('#pwd'), $loginBtn = $('#btn-login'), $mask = $('#retrive-pwd-mask'), $ways = $('#retrive-pwd-ways'), accPass = false, pwdPass = false; var api = require("js/passport/api"); var tip = require("js/plugin/tip"); var trim = $.trim; var showErrTip = tip.show; //登录按钮状态切换 function switchLoginBtnStatus() { if (accPass && pwdPass) { $loginBtn.removeClass('disable'); } else { $loginBtn.addClass('disable'); } } //显示找回密码面板 function showRetrivePanel() { $mask.show(); $ways.show(); } //隐藏找回密码面板 function hideRetrivePanel() { $mask.hide(); $ways.hide(); } //密码显示与隐藏 api.bindEyesEvt(); //清空账号输入框 api.bindClearEvt(); $account.bind('input', function() { if (trim($account.val()) !== '') { accPass = true; } else { accPass = false; } switchLoginBtnStatus(); }); $pwd.bind('input', function() { if (trim($pwd.val()) === '') { pwdPass = false; } else { pwdPass = true; } switchLoginBtnStatus(); }); // Login $loginBtn.on('touchstart', function() { var acc = trim($account.val()), pwd = trim($pwd.val()); if ($loginBtn.hasClass('disable')) { return; } $loginBtn.text('正在登录...').addClass('disable'); //验证账号(数字或者邮箱)和密码合理性 if ((/^[0-9]+$/.test(acc) || api.emailRegx.test(acc)) && api.pwdValidate(pwd)) { $.ajax({ type: 'POST', url: '/passport/login/auth', data: { account: acc, password: pwd }, success: function(data) { var res, time; if (data.code === 200) { res = data.data; $.ajax({ url: res.session, dataType: 'jsonp', success: function() { clearTimeout(time); //Cookie写入成功后,1s后跳转页面 setTimeout(function() { location.href = res.href; }, 1000); } }); //3秒后强制跳转 time = setTimeout(function() { location.href = res.href; }, 3000); showErrTip('登录成功'); } else { showErrTip(data.message); } }, error: function() { showErrTip('网络断开连接啦~'); }, complete: function() { $loginBtn.text('登录').removeClass('disable'); } }); } else { showErrTip('账号或密码有错误,请重新输入'); } }); $('#forget-pwd').on('touchstart', function() { showRetrivePanel(); }); $mask.on('touchstart', function() { hideRetrivePanel(); }); $('#cancel-retrive').on('touchstart', function(e) { e.preventDefault(); hideRetrivePanel(); }); //对初始有默认值的情况去初始化登录按钮状态 $account.trigger('input'); $pwd.trigger('input'); }); define("js/passport/login/international", ["jquery"], function(require, exports, module){ /** * 国际账号登录 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/8 */ var $ = require("jquery"); var $phoneNum = $('#phone-num'), $countrySelect = $('#country-select'), $areaCode = $('#area-code'), $pwd = $('#pwd'), $loginBtn = $('#btn-login'), pnPass = false, pwdPass = false; var api = require("js/passport/api"); var tip = require("js/plugin/tip"); var trim = $.trim; var showErrTip = tip.show; //登录按钮状态切换 function switchLoginBtnStatus() { if (pnPass && pwdPass) { $loginBtn.removeClass('disable'); } else { $loginBtn.addClass('disable'); } } //Android-UC下显示select的direction:rtl无效的临时解决办法 api.selectCssHack($countrySelect); //显示隐藏密码 api.bindEyesEvt(); //清空手机号码 api.bindClearEvt(); $phoneNum.bind('input', function() { if (trim($phoneNum.val()) === '') { pnPass = false; } else { pnPass = true; } switchLoginBtnStatus(); }); $pwd.bind('input', function() { var pwd = trim($pwd.val()); if (pwd === '') { pwdPass = false; } else { pwdPass = true; } switchLoginBtnStatus(); }); $countrySelect.change(function() { $areaCode.text($countrySelect.val()); }); $loginBtn.on('touchstart', function() { var pn = trim($phoneNum.val()), areaCode = $countrySelect.val(), pwd = trim($pwd.val()); if ($loginBtn.hasClass('disable')) { return; } $loginBtn.text('正在登录...').addClass('disable'); if (api.phoneRegx[areaCode].test(pn) && api.pwdValidate(pwd)) { $.ajax({ type: 'POST', url: '/passport/login/auth', data: { areaCode: areaCode.replace('+', ''), account: pn, password: pwd }, success: function(data) { var res, time; if (data.code === 200) { res = data.data; showErrTip('登录成功'); $.ajax({ url: res.session, dataType: 'jsonp', success: function() { clearTimeout(time); //Cookie写入成功后,1s后跳转页面 setTimeout(function() { location.href = res.href; }, 1000); } }); //3秒后强制跳转 time = setTimeout(function() { location.href = res.href; }, 3000); showErrTip('登录成功'); } else { showErrTip(data.message); } }, error: function() { showErrTip('网络断开连接啦~'); }, complete: function() { $loginBtn.text('登录').removeClass('disable'); } }); } else { showErrTip('账号或密码有错误,请重新输入'); } }); //对初始有默认值的情况去初始化登录按钮状态 $phoneNum.trigger('input'); $pwd.trigger('input'); }); define("js/passport/back/mobile", ["jquery"], function(require, exports, module){ /** * 找回密码-手机 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/8 */ var $ = require("jquery"); var $phoneNum = $('#phone-num'), $countrySelect = $('#country-select'), $areaCode = $('#area-code'), $btnNext = $('#btn-next'); var api = require("js/passport/api"); var tip = require("js/plugin/tip"); var trim = $.trim; var showErrTip = tip.show; api.selectCssHack($('#country-select')); api.bindClearEvt(); $phoneNum.bind('input', function() { if (trim($phoneNum.val()) === '') { $btnNext.addClass('disable'); } else { $btnNext.removeClass('disable'); } }); $countrySelect.change(function() { $areaCode.text($countrySelect.val()); }); $btnNext.on('touchstart', function() { var pn = trim($phoneNum.val()), area = $countrySelect.val(); if ($btnNext.hasClass('disable')) { return; } if (api.phoneRegx[area].test(pn)) { $.ajax({ url: '/passport/back/sendcode', type: 'POST', data: { areaCode: area.replace('+', ''), phoneNum: pn }, success: function(data) { if (data.code === 200) { location.href = data.data; } else { showErrTip(data.message); } } }); } else { showErrTip('手机号格式不正确,请重新输入'); } }); }); define("js/passport/back/code", ["jquery"], function(require, exports, module){ /** * 找回密码-验证码 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/8 */ require("js/passport/code")(false); }); define("js/passport/back/email", ["jquery"], function(require, exports, module){ /** * 找回密码-邮箱找回 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/8 */ var $ = require("jquery"); var $email = $('#email'), $btnSure = $('#btn-sure'); var api = require("js/passport/api"); var tip = require("js/plugin/tip"); var trim = $.trim; var showErrTip = tip.show; api.bindClearEvt(); $email.bind('input', function() { if (trim($email.val()) === '') { $btnSure.addClass('disable'); } else { $btnSure.removeClass('disable'); } }); $btnSure.on('touchstart', function() { var email = trim($email.val()); if ($btnSure.hasClass('disable')) { return; } if (api.emailRegx.test(email)) { $.ajax({ url: '/passport/back/sendemail', type: 'POST', data: { email: email }, success: function(data) { if (data.code === 200) { location.href = data.data; } else { showErrTip(data.message); } } }); } else { showErrTip('邮箱格式不正确,请重新输入'); } }); }); define("js/passport/back/email-success", ["jquery"], function(require, exports, module){ /** * 找回密码-邮箱找回成功 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/8 */ var $ = require("jquery"); var $resend = $('#resend'); var tip = require("js/plugin/tip"), showErrTip = tip.show; $resend.on('touchstart', function(e) { e.preventDefault(); $.ajax({ url: $resend.data('url'), type: 'GET', success: function(data) { if (data.code === 200) { showErrTip(data.message); } else { showErrTip(data.message); } } }); }); }); define("js/passport/back/new-password", ["jquery"], function(require, exports, module){ /** * 密码找回-新密码 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/8 */ var $ = require("jquery"); var $pwd = $('#pwd'), $btnOk = $('#btn-ok'); var api = require("js/passport/api"); var tip = require("js/plugin/tip"); var trim = $.trim; var showErrTip = tip.show; var $phoneNum = $('#phone-num'); api.bindEyesEvt({ status: 'open' }); $pwd.bind('input', function() { if (trim($pwd.val()) === '') { $btnOk.addClass('disable'); } else { $btnOk.removeClass('disable'); } }); $btnOk.on('touchstart', function() { var pwd = trim($pwd.val()), mobileBack = true, setting, url; if ($btnOk.hasClass('disable')) { return; } setting = { password: pwd }; if ($phoneNum.length === 0) { mobileBack = false; } if (mobileBack) { $.extend(setting, { phoneNum: $phoneNum.val(), areaCode: $('#areaCode').val(), token: $('#token').val() }); url = '/passport/back/passwordByMobile'; } else { $.extend(setting, { code: $('#email-code').val() }); url = '/passport/back/passwordByEmail'; } if (api.pwdValidate(pwd)) { $.ajax({ type: 'POST', url: url, data: setting, success: function(data) { if (data.code === 200) { showErrTip('密码修改成功'); //1000ms后跳转页面 setTimeout(function() { location.href = data.data; }, 1000); } else { showErrTip(data.message); } } }); } else { showErrTip('密码6-20位,请重新输入'); } }); }); define("js/product/entry", ["jquery","swiper","lazyload","hammer","index"], function(require, exports, module){ /** * 产品打包入口 * @author: liangzhifeng<zhifeng.liang@yoho.cn> * @date: 2015/10/12 */ require("js/product/newsale/newarrival"); require("js/product/newsale/discount"); require("js/product/list"); require("js/product/detail/detail"); require("js/product/detail/consultform"); require("js/product/newsale/hot-rank"); }); define("js/product/newsale/newarrival", ["jquery","swiper","lazyload","hammer","index"], function(require, exports, module){ /** * 新品到着 * @author: liangzhifeng<zhifeng.liang@yoho.cn> * @date: 2015/10/24 */ var $ = require("jquery"), Swiper = require("swiper"), lazyLoad = require("lazyload"); var swiper, $ngc, $pgc, $dgc; var tip = require("js/plugin/tip"), filter = require("js/plugin/filter"), loading = require("js/plugin/loading"); var $goodsContainer = $('#goods-container'), $goodsChildren = $goodsContainer.children(), $ngc = $($goodsChildren.get(0)), $pgc = $($goodsChildren.get(1)).addClass('hide'), $dgc = $($goodsChildren.get(2)).addClass('hide'); var winH = $(window).height(), noResult = '<p class="no-result">未找到相关搜索结果</p>'; //默认筛选条件 var defaultOpt = require("js/product/query-param"); var storeOpt = $.extend({}, defaultOpt); //存储默认筛选条件以便重置 var now = new Date(), month = now.getMonth() + 1, date = now.getDate(); var $listNav = $('#list-nav'), //导航数据信息 navInfo = { today: { reload: true, page: 0, end: false }, week: { reload: true, page: 0, end: false }, sale: { reload: true, page: 0, end: false } }, $pre = $listNav.find('.active'), //纪录进入筛选前的active项,初始为选中项 searching; require("js/product/suspend-cart"); //悬浮购物车 $('#today a').text(month + '月' + date + '号'); if ($('.swiper-container .swiper-slide').length > 1) { swiper = new Swiper('.swiper-container', { lazyLoading: true, lazyLoadingInPrevNext: true, loop: true, autoplay: 3000, autoplayDisableOnInteraction: true, paginationClickable: true, pagination: '.banner-top .pagination-inner' }); } /** * 筛选注册的回调,筛选子项点击后逻辑 * 需要执行search的场景:1.点选筛选项;2.relaod为true时切换导航;3.下拉加载 * @param opt {type, id} */ function search(opt) { var setting = {}, ext, att, nav, navType, dayLimit, page; if (searching) { return; } if (opt) { //筛选项变更则重置reload为true for (att in navInfo) { if (navInfo.hasOwnProperty(att)) { navInfo[att].reload = true; } } //处理active状态 $listNav.children('.active').removeClass('active'); $pre.addClass('active'); switch (opt.type) { case 'gender': ext = { gender: opt.id }; break; case 'brand': ext = { brand: opt.id }; break; case 'sort': ext = { sort: opt.id }; break; case 'color': ext = { color: opt.id }; break; case 'size': ext = { size: opt.id }; break; case 'price': ext = { price: opt.id }; break; case 'discount': ext = { discount: opt.id }; break; case 'limit': ext = { limit: opt.id }; break; case 'channel': ext = { channel: opt.id }; break; case 'p_d': ext = { p_d: opt.id }; break; } $.extend(defaultOpt, ext); //扩展筛选项 } //导航类别 if ($pre.hasClass('today')) { navType = 'today'; dayLimit = 1; } else if ($pre.hasClass('week')) { navType = 'week'; dayLimit = 2; } else if ($pre.hasClass('sale')) { navType = 'sale'; dayLimit = 3; } nav = navInfo[navType]; page = nav.page + 1; if (nav.reload) { page = 1; } else if (nav.end) { //不需要重新加载并且数据请求结束 return; } $.extend(setting, defaultOpt, { dayLimit: dayLimit, page: page }); searching = true; loading.showLoadingMask(); $.ajax({ type: 'GET', url: '/product/newsale/selectNewSale', data: setting, success: function(data) { var $container, num; switch (navType) { case 'today': $container = $ngc; break; case 'week': $container = $pgc; break; case 'sale': $container = $dgc; break; } if (data === ' ') { nav.end = true; if (nav.reload) { $container.html(noResult); } } else { if (nav.reload) { $container.html(data); lazyLoad($container.find('.lazy')); } else { num = $container.find('.good-info').length; $container.append(data); //lazy good-infos who append in lazyLoad($container.find('.good-info:gt(' + (num - 1) + ') .lazy')); } } nav.reload = false; nav.page = page; searching = false; loading.hideLoadingMask(); window.rePosFooter(); }, error: function() { tip.show('网络断开连接了~'); searching = false; loading.hideLoadingMask(); } }); } $.ajax({ type: 'GET', url: '/product/newsale/filter', data: defaultOpt, success: function(data) { $goodsContainer.append(data); //初始化filter&注册filter回调 filter.initFilter({ fCbFn: search, hCbFn: function() { //切换active状态到$pre上 $pre.addClass('active'); $pre.siblings('.filter').removeClass('active'); } }); } }); lazyLoad($('.lazy')); $listNav.bind('contextmenu', function(e) { return false; }); //导航栏点击逻辑说明: //1.点击非active项时切换active状态 //2.价格和折扣active状态时继续点击切换排序 //3.筛选无active时点击展开筛选面板 //4.筛选有active时点击隐藏筛选面板并恢复点击筛选前active项的active状态 //5.当前active为筛选并且点击其他项时,隐藏筛选面板 // navHammer = new Hammer($listNav[0]); $listNav.on('touchend touchcancel', function(e) { var $this = $(e.target).closest('li'), nav, navType, $active; e.preventDefault(); if ($this.hasClass('filter')) { //筛选面板切换状态 if ($this.hasClass('active')) { filter.hideFilter(); //点击筛选钱的active项回复active $pre.addClass('active'); $this.removeClass('active'); } else { $pre = $this.siblings('.active'); $pre.removeClass('active'); $this.addClass('active'); filter.showFilter(); } } else { if ($this.hasClass('today')) { navType = 'today'; } else if ($this.hasClass('week')) { navType = 'week'; } else if ($this.hasClass('sale')) { navType = 'sale'; } nav = navInfo[navType]; if (!($this.hasClass('active'))) { $active = $this.siblings('.active'); $pre = $this; //$pre为除筛选导航的其他导航项,若当前active的为筛选,则把$pre置为当前点击项 if ($active.hasClass('filter')) { //若之前active项为筛选,则隐藏筛选面板 filter.hideFilter(); } else { //切换container显示 $goodsContainer.children('.container:not(.hide)').addClass('hide'); switch (navType) { case 'today': $ngc.removeClass('hide'); break; case 'week': $pgc.removeClass('hide'); break; case 'sale': $dgc.removeClass('hide'); break; } //重置筛选项 filter.resetFilter(); defaultOpt = $.extend({}, storeOpt); } $active.removeClass('active'); $this.addClass('active'); } if (nav.reload) { search(); } } e.stopPropagation(); }); function scrollHandler() { //当scroll到1/4$goodsContainer高度后继续请求下一页数据 if ($(window).scrollTop() + winH > $(document).height() - 0.25 * $goodsContainer.height() - 50) { if ($pre !== undefined) { search(); } } } //srcoll to load more $(window).scroll(function() { window.requestAnimationFrame(scrollHandler); }); //初始请求最新第一页数据 search(); $listNav.on('touchstart', 'li', function(e) { $(this).addClass('bytouch'); }).on('touchend touchcancel', function() { $listNav.find('li').removeClass('bytouch'); }); }); define("js/plugin/filter", ["jquery","hammer"], function(require, exports, module){ /** * 筛选JS * 暴露三个接口:注册回调、显示filter、隐藏filter * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/19 */ var $ = require("jquery"), Hammer = require("hammer"); var $filter; var fCbFn, hCbFn; //筛选和关闭的回调 var missStatus; //是否忽略选中状态 //隐藏筛选界面 function hideFilter() { $filter.addClass('hide'); } //显示筛选界面 function showFilter() { $filter.removeClass('hide'); } // 一级菜单点击时背景高亮 function highlightMainItem() { var $mainItem = $('.filter-body .classify'); $mainItem.on('touchstart', '.shower', function() { $mainItem.removeClass('highlight'); $(this).addClass('highlight'); }).on('touchend touchcancel', '.shower', function() { $(this).removeClass('highlight'); }); } // 子菜单点击时背景高亮 function highlightSubItem() { var $subItem = $('.filter-body .sub-item'); $subItem.on('touchstart', function() { $subItem.removeClass('highlight'); $(this).addClass('highlight'); }).on('touchend touchcancel', function() { $(this).removeClass('highlight'); }); } //主筛选项Tap事件句柄 function classifyTapEvt($this) { if ($this.hasClass('active')) { return; } $this.siblings('.active').removeClass('active'); $this.addClass('active'); } //子筛选项选中处理 function setSubClassify($this) { var $sub = $this.closest('.sub-classify'); var $shower = $sub.siblings('.shower'); var html, shower; if ($this.hasClass('chosed')) { return $sub; } $sub.children('.chosed').removeClass('chosed'); $this.addClass('chosed'); html = $.trim($this.html()); shower = $.trim($shower.html()); $shower.html( shower.substring(0, shower.indexOf('</span>') + 7) + //拆分出shower的title html.substring(0, html.indexOf('<i')) //拆分选中筛选值 ); if ($this.index() === 0) { $shower.addClass('default'); } else { $shower.removeClass('default'); } return $sub; } //子筛选项Tap句柄 function subClassifyTapEvt($this) { var id = $this.data('id'); var $sub; $sub = setSubClassify($this); if (fCbFn) { fCbFn({ type: $sub.data('type'), id: id }); } hideFilter(); } //初始化筛选 function initFilter(opt) { var filterHammer; //注册回调 fCbFn = opt.fCbFn; hCbFn = opt.hCbFn; missStatus = opt.missStatus; highlightMainItem(); highlightSubItem(); $filter = $('.filter-mask'); filterHammer = new Hammer($filter[0]); filterHammer.on('tap', function(e) { var $this = $(e.target), $cur; e.preventDefault();//防止透点 if ($this.closest('.filter-body').length > 0) { $cur = $this.closest('.sub-item'); if ($cur.length > 0) { //tap subclassify $cur = $this.closest('li'); subClassifyTapEvt($cur); } else { //tap classify $cur = $this.closest('.classify-item'); e.srcEvent.stopPropagation(); classifyTapEvt($cur); } } else { hideFilter(); if (hCbFn) { hCbFn(); } } }); } //重置筛选面板 function resetFilter() { if (typeof $filter === 'undefined') { return; } //重置子筛选项 $('.sub-classify').each(function() { setSubClassify($(this).children(':first-child')); }); //重置主筛选项 classifyTapEvt($('.classify > :first-child')); } exports.initFilter = initFilter; exports.showFilter = showFilter; exports.hideFilter = hideFilter; exports.resetFilter = resetFilter; }); define("js/product/query-param", ["jquery"], function(require, exports, module){ /** * 提取查询参数 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/11/19 */ var $ = require("jquery"), opt = {}; $('.query-param').each(function() { var $this = $(this); opt[$this.data('attr')] = $this.val(); }); module.exports = opt; }); define("js/product/suspend-cart", ["jquery"], function(require, exports, module){ /** * 悬浮购物车 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/11/1 */ var $ = require("jquery"); var $cart = $('#suspend-cart'); $.ajax({ type: 'GET', url: '/cart/index/count', success: function(data) { if (data.code === 200) { $cart.find('.cart-count').html(data.data.cart_goods_count).removeClass('hide'); } } }); }); define("js/product/newsale/discount", ["jquery","swiper","lazyload","hammer","index"], function(require, exports, module){ /** * 商品列表页 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/20 */ var $ = require("jquery"), Swiper = require("swiper"), lazyLoad = require("lazyload"); var swiper; var tip = require("js/plugin/tip"), filter = require("js/plugin/filter"), loading = require("js/plugin/loading"); var $goodsContainer = $('#goods-container'), $goodsChildren = $goodsContainer.children(), $ngc = $($goodsChildren.get(0)), $pgc = $($goodsChildren.get(1)), $dgc = $($goodsChildren.get(2)); var winH = $(window).height(), noResult = '<p class="no-result">未找到相关搜索结果</p>'; //默认筛选条件 var defaultOpt = require("js/product/query-param"); var $listNav = $('#list-nav'), //导航数据信息 navInfo = { newest: { order: 1, reload: true, page: 0, end: false }, price: { order: 0, reload: true, page: 0, end: false }, discount: { order: 0, reload: true, page: 0, end: false } }, $pre = $listNav.find('.active'), //纪录进入筛选前的active项,初始为选中项 searching; require("js/product/suspend-cart"); //悬浮购物车 if ($('.swiper-container .swiper-slide').length > 1) { swiper = new Swiper('.swiper-container', { lazyLoading: true, lazyLoadingInPrevNext: true, loop: true, autoplay: 3000, autoplayDisableOnInteraction: true, paginationClickable: true, pagination: '.banner-top .pagination-inner' }); } /** * 筛选注册的回调,筛选子项点击后逻辑 * 需要执行search的场景:1.点选筛选项;2.relaod为true时切换导航;3.下拉加载 * @param opt {type, id} */ function search(opt) { var setting = {}, ext, att, nav, navType, page; if (searching) { return; } if (opt) { //筛选项变更则重置reload为true for (att in navInfo) { if (navInfo.hasOwnProperty(att)) { navInfo[att].reload = true; } } //处理active状态 $listNav.children('.active').removeClass('active'); $pre.addClass('active'); switch (opt.type) { case 'gender': ext = { gender: opt.id }; break; case 'brand': ext = { brand: opt.id }; break; case 'sort': ext = { sort: opt.id }; break; case 'color': ext = { color: opt.id }; break; case 'size': ext = { size: opt.id }; break; case 'price': ext = { price: opt.id }; break; case 'discount': ext = { discount: opt.id }; break; } $.extend(defaultOpt, ext); //扩展筛选项 } //导航类别 if ($pre.hasClass('new')) { navType = 'newest'; } else if ($pre.hasClass('price')) { navType = 'price'; } else if ($pre.hasClass('discount')) { navType = 'discount'; } nav = navInfo[navType]; page = nav.page + 1; if (nav.reload) { page = 1; } else if (nav.end) { //不需要重新加载并且数据请求结束 return; } $.extend(setting, defaultOpt, { type: navType, order: nav.order, page: page }); searching = true; loading.showLoadingMask(); $.ajax({ type: 'GET', url: '/product/newsale/selectNewSale', data: setting, success: function(data) { var $container, num; switch (navType) { case 'newest': $container = $ngc; break; case 'price': $container = $pgc; break; case 'discount': $container = $dgc; break; } if (data === ' ') { nav.end = true; if (nav.reload) { $container.html(noResult); } } else { if (nav.reload) { $container.html(data); lazyLoad($container.find('.lazy')); } else { num = $container.find('.good-info').length; $container.append(data); //lazy good-infos who append in lazyLoad($container.find('.good-info:gt(' + (num - 1) + ') .lazy')); } } nav.reload = false; nav.page = page; searching = false; loading.hideLoadingMask(); window.rePosFooter(); }, error: function() { tip.show('网络断开连接了~'); searching = false; loading.hideLoadingMask(); } }); } $.ajax({ type: 'GET', url: '/product/newsale/filter', data: defaultOpt, success: function(data) { $goodsContainer.append(data); //初始化filter&注册filter回调 filter.initFilter({ fCbFn: search, hCbFn: function() { //切换active状态到$pre上 $pre.addClass('active'); $pre.siblings('.filter').removeClass('active'); }, missStatus: true }); } }); lazyLoad($('.lazy')); //导航栏点击逻辑说明: //1.点击非active项时切换active状态 //2.价格和折扣active状态时继续点击切换排序 //3.筛选无active时点击展开筛选面板 //4.筛选有active时点击隐藏筛选面板并恢复点击筛选前active项的active状态 //5.当前active为筛选并且点击其他项时,隐藏筛选面板 $listNav.bind('contextmenu', function(e) { return false; }); $listNav.on('touchend touchcancel', function(e) { var $this = $(e.target).closest('li'), nav, navType, $active; e.preventDefault(); if (typeof $this === 'undefined' || $this.length === 0) { return; } if ($this.hasClass('filter')) { //筛选面板切换状态 if ($this.hasClass('active')) { filter.hideFilter(); //点击筛选钱的active项回复active $pre.addClass('active'); $this.removeClass('active'); } else { $pre = $this.siblings('.active'); $pre.removeClass('active'); $this.addClass('active'); filter.showFilter(); } } else { if ($this.hasClass('new')) { navType = 'newest'; } else if ($this.hasClass('price')) { navType = 'price'; } else if ($this.hasClass('discount')) { navType = 'discount'; } nav = navInfo[navType]; if ($this.hasClass('active')) { //最新无排序切换 if ($this.hasClass('new')) { return; } if ($this.hasClass('price') || $this.hasClass('discount')) { // 价格/折扣切换排序状态 $this.find('.icon > .iconfont').toggleClass('cur'); $pre = $this; //更新pre为当前项 nav.reload = true; //重置reload,HTML会被替换为逆序的HTML nav.order = nav.order === 0 ? 1 : 0; //切换排序 } } else { $active = $this.siblings('.active'); $pre = $this; //$pre为除筛选导航的其他导航项,若当前active的为筛选,则把$pre置为当前点击项 if ($active.hasClass('filter')) { //若之前active项为筛选,则隐藏筛选面板 filter.hideFilter(); } else { //切换container显示 $goodsContainer.children('.container:not(.hide)').addClass('hide'); switch (navType) { case 'newest': $ngc.removeClass('hide'); break; case 'price': $pgc.removeClass('hide'); break; case 'discount': $dgc.removeClass('hide'); break; } } $active.removeClass('active'); $this.addClass('active'); } if (nav.reload) { search(); } } e.stopPropagation(); }); function scrollHandler() { //当scroll到1/4$goodsContainer高度后继续请求下一页数据 if ($(window).scrollTop() + winH > $(document).height() - 0.25 * $goodsContainer.height() - 50) { if ($pre !== undefined) { search(); } } } //srcoll to load more $(window).scroll(function() { window.requestAnimationFrame(scrollHandler); }); //初始请求最新第一页数据 search(); $listNav.on('touchstart', 'li', function(e) { $(this).addClass('bytouch'); }).on('touchend touchcancel', function() { $listNav.find('li').removeClass('bytouch'); }); }); define("js/product/list", ["jquery","hammer","lazyload"], function(require, exports, module){ /** * 商品列表页 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/10/20 */ var $ = require("jquery"), Hammer = require("hammer"), lazyLoad = require("lazyload"); //品牌页参数 var $brandHeader = $('#brand-header'), $introBox = $('#intro-box'); var filter = require("js/plugin/filter"); var writeSearch = require("js/index/write-search"); var tip = require("js/plugin/tip"); var loading = require("js/plugin/loading"); var $goodsContainer = $('#goods-container'), $ngc = $goodsContainer.children('.new-goods'), $pgc = $goodsContainer.children('.price-goods'), $dgc = $goodsContainer.children('.discount-goods'); var winH = $(window).height(); var $input = $('#search-input input'), $icon = $('.search-icon'), $clear = $('#search-input .clear-input'); //默认筛选条件 var defaultOpt = require("js/product/query-param"); var $listNav = $('#list-nav'), //导航数据信息 navInfo = { newest: { order: 1, reload: true, page: 0, end: false }, price: { order: 0, reload: true, page: 0, end: false }, discount: { order: 0, reload: true, page: 0, end: false } }, $pre = $listNav.find('.active'), //纪录进入筛选前的active项,初始为选中项 searching, btnIntroHammer, introHammer, brandColHammer; $input.on('input', function() { if ($input.val() === '') { $icon.css('color', '#b2b2b2'); $clear.addClass('hide'); } else { $icon.css('color', '#666'); $clear.removeClass('hide'); } }); $clear.on('touchend', function() { $input.val('').trigger('input'); }); /** * 手动触发搜索 */ $('#search').on('touchend', function() { $(this).closest('form').submit(); return false; }); /** * 筛选注册的回调,筛选子项点击后逻辑 * 需要执行search的场景:1.点选筛选项;2.relaod为true时切换导航;3.下拉加载 * @param opt {type, id} */ function search(opt) { var setting = {}, ext, att, nav, navType, page; if (searching) { return; } if (opt) { //筛选项变更则重置reload为true for (att in navInfo) { if (navInfo.hasOwnProperty(att)) { navInfo[att].reload = true; } } //处理active状态 $listNav.children('.active').removeClass('active'); $pre.addClass('active'); switch (opt.type) { case 'gender': ext = { gender: opt.id }; break; case 'brand': ext = { brand: opt.id }; break; case 'sort': ext = { sort: opt.id }; break; case 'color': ext = { color: opt.id }; break; case 'size': ext = { size: opt.id }; break; case 'price': ext = { price: opt.id }; break; case 'discount': ext = { discount: opt.id }; break; } $.extend(defaultOpt, ext); //扩展筛选项 } //导航类别 if ($pre.hasClass('new')) { navType = 'newest'; } else if ($pre.hasClass('price')) { navType = 'price'; } else if ($pre.hasClass('discount')) { navType = 'discount'; } nav = navInfo[navType]; page = nav.page + 1; if (nav.reload) { page = 1; } else if (nav.end) { //不需要重新加载并且数据请求结束 return; } $.extend(setting, defaultOpt, { type: navType, order: nav.order, page: page }); searching = true; loading.showLoadingMask(); $.ajax({ type: 'GET', url: '/index/search/search', data: setting, success: function(data) { var noResult = '<p class="no-result">未找到相关搜索结果</p>', num, $container; switch (navType) { case 'newest': $container = $ngc; break; case 'price': $container = $pgc; break; case 'discount': $container = $dgc; break; } if (data === ' ') { nav.end = true; if (nav.reload) { $container.html(noResult); } } else { if (nav.reload) { $container.html(data); lazyLoad($container.find('.lazy')); } else { num = $container.find('.good-info').length; $container.append(data); //lazy good-infos who append in lazyLoad($container.find('.good-info:gt(' + (num - 1) + ') .lazy')); } } nav.reload = false; nav.page = page; searching = false; loading.hideLoadingMask(); window.rePosFooter(); } }); } require("js/product/suspend-cart"); //悬浮购物车 $.ajax({ type: 'GET', url: '/search/filter', data: defaultOpt, success: function(data) { $goodsContainer.append(data); //初始化filter&注册filter回调 filter.initFilter({ fCbFn: search, hCbFn: function() { //切换active状态到$pre上 $pre.addClass('active'); $pre.siblings('.filter').removeClass('active'); } }); } }); lazyLoad($('.lazy')); writeSearch.bindWirteLocal($('#search-form')); //导航栏点击逻辑说明: //1.点击非active项时切换active状态 //2.价格和折扣active状态时继续点击切换排序 //3.筛选无active时点击展开筛选面板 //4.筛选有active时点击隐藏筛选面板并恢复点击筛选前active项的active状态 //5.当前active为筛选并且点击其他项时,隐藏筛选面板 $listNav.bind('contextmenu', function(e) { return false; }); $listNav.on('touchend touchcancel', function(e) { var $this = $(e.target).closest('li'), nav, navType, $active; if ($this.hasClass('filter')) { //筛选面板切换状态 if ($this.hasClass('active')) { filter.hideFilter(); //点击筛选钱的active项回复active $pre.addClass('active'); $this.removeClass('active'); } else { $pre = $this.siblings('.active'); $pre.removeClass('active'); $this.addClass('active'); filter.showFilter(); } } else { if ($this.hasClass('new')) { navType = 'newest'; } else if ($this.hasClass('price')) { navType = 'price'; } else if ($this.hasClass('discount')) { navType = 'discount'; } nav = navInfo[navType]; if ($this.hasClass('active')) { //最新无排序切换 if ($this.hasClass('new')) { return; } if ($this.hasClass('price') || $this.hasClass('discount')) { // 价格/折扣切换排序状态 $this.find('.icon > .iconfont').toggleClass('cur'); $pre = $this; //更新pre为当前项 nav.reload = true; //重置reload,HTML会被替换为逆序的HTML nav.order = nav.order === 0 ? 1 : 0; //切换排序 } } else { $active = $this.siblings('.active'); $pre = $this; //$pre为除筛选导航的其他导航项,若当前active的为筛选,则把$pre置为当前点击项 if ($active.hasClass('filter')) { //若之前active项为筛选,则隐藏筛选面板 filter.hideFilter(); } else { //切换container显示 $goodsContainer.children('.container:not(.hide)').addClass('hide'); switch (navType) { case 'newest': $ngc.removeClass('hide'); break; case 'price': $pgc.removeClass('hide'); break; case 'discount': $dgc.removeClass('hide'); break; } } $active.removeClass('active'); $this.addClass('active'); } if (nav.reload) { search(); } } }); function scrollHandler() { //当scroll到1/4$goodsContainer高度后继续请求下一页数据 if ($(window).scrollTop() + winH > $(document).height() - 0.25 * $goodsContainer.height()) { search(); } } //srcoll to load more $(window).scroll(function() { window.requestAnimationFrame(scrollHandler); }); if ($brandHeader.length > 0) { //品牌介绍 btnIntroHammer = new Hammer($brandHeader.children('.btn-intro')[0]); btnIntroHammer.on('tap', function() { $introBox.removeClass('hide'); //防止混合scroll发生 $('body').addClass('overflow-hidden'); }); //关闭品牌介绍 introHammer = new Hammer(document.getElementById('intro-box')); introHammer.on('tap', function(e) { var $this = $(e.target); e.srcEvent.preventDefault(); //关闭品牌介绍box if ($this.closest('#brand-intro').length === 0 || $this.hasClass('close-intro')) { $introBox.addClass('hide'); $('body').removeClass('overflow-hidden'); } }); //品牌收藏 brandColHammer = new Hammer($brandHeader.children('.btn-col')[0]); brandColHammer.on('tap', function(e) { var $this = $(e.target).closest('.btn-col'); var id = $brandHeader.data('id'), opt; if ($this.hasClass('coled')) { opt = 'cancel'; } else { opt = 'ok'; } $.ajax({ type: 'POST', url: '/product/opt/favoriteBrand', data: { id: id, opt: opt }, success: function(data) { if (data.code === 200) { $this.toggleClass('coled'); //提示 if (opt === 'ok') { tip.show('添加收藏成功'); } else { tip.show('取消收藏成功'); } } else if (data.code === 400) { location.href = data.data;//未登录跳转登录页 } else { tip.show(data.message); } }, error: function() { tip.show('网络断开连接了~'); } }); }); } //初始请求最新第一页数据 search(); $listNav.on('touchstart', 'li', function() { $listNav.find('li').removeClass('bytouch'); $(this).addClass('bytouch'); }).on('touchend touchcancel', 'li', function() { $listNav.find('li').removeClass('bytouch'); }); // 用于统计点击了商品列表的第几个商品,序号从1开始计算。 if (window._yas) { window._yas(1 * new Date(), '1.0.13.2', 'yohobuy_m', window._ozuid, '', '#goods-container >div >div .good-thumb >img'); } }); define("js/product/detail/detail", ["jquery","swiper","hammer","lazyload","index"], function(require, exports, module){ /** * 商品详情 * @author: liangzhifeng<zhifeng.liang@yoho.cn> * @date: 2015/10/20 */ var $ = require("jquery"), Swiper = require("swiper"), Hammer = require("hammer"), lazyLoad = require("lazyload"); var goodsSwiper, $discountFolder = $('.goodsDiscount .discount-folder'), $discountArrow = $('.goodsDiscount .first-item span'); var goodsDiscountEl = document.getElementById('goodsDiscount'), goodsDiscountHammer = goodsDiscountEl && new Hammer(goodsDiscountEl), $discountFirstItem = $(goodsDiscountEl).find('.first-item'); var $cart = $('.cart-bar'); require("js/product/detail/desc"); require("js/product/detail/comments-consults"); require("js/product/recommend-for-you-product-desc"); //add extra marign-bottom for footer to show the yoho copyright function showFooter() { var $cartBar = $('.cart-bar'); var timer = setInterval(function() { if ($cartBar) { window.reMarginFooter('.cart-bar'); clearInterval(timer); } else { $cartBar = $('.cart-bar'); } }, 200); } showFooter(); lazyLoad($('img.lazy')); //顶部swiper goodsSwiper = new Swiper('.banner-swiper', { lazyLoading: true, lazyLoadingInPrevNext: true, paginationClickable: true, pagination: '.banner-top .pagination-inner', nextButton: '.my-swiper-button-next', prevButton: '.my-swiper-button-prev', spaceBetween: 3 }); //初始化goods-discount if (0 === $discountFolder.children().length) { $discountFolder.css('display', 'none'); $discountArrow.html(''); } //goods-discount下拉按钮点击事件 if (goodsDiscountHammer && $discountFolder.children().length > 0) { goodsDiscountHammer.on('tap', function(e) { if ($discountFolder.is(':hidden')) { $discountFirstItem.removeClass('short-text'); $discountArrow.removeClass('icon-down').addClass('icon-up').html(''); $discountFolder.slideDown(); } else { $discountFirstItem.addClass('short-text'); $discountArrow.removeClass('icon-up').addClass('icon-down').html(''); $discountFolder.slideUp(); } }); } //购物车商品数量 $.ajax({ type: 'GET', url: '/cart/index/count', success: function(data) { if (data.code === 200) { $cart.find('.num-tag').html(data.data.cart_goods_count).removeClass('hide'); } } }); if ($('.good-detail-page').length > 0) { $('#yoho-footer').css('border-top', '1px solid #e0e0e0'); } require("js/product/detail/like"); }); define("js/product/detail/desc", ["jquery","lazyload","swiper","index"], function(require, exports, module){ /** * 商品详情 --异步加载页面下半部分 * @author: liangzhifeng<zhifeng.liang@yoho.cn> * @date: 2015/11/18 */ var $ = require("jquery"), lazyLoad = require("lazyload"), Swiper = require("swiper"), loading = require("js/plugin/loading"), tip = require("js/plugin/tip"); var introUrl = $('#introUrl').val(), winH = $(window).height(), $productDesc, searching = false, end = false; var sizeSwiper, refSwiper; //判断是否要显示向左滑动提示 function hiddenTips($ele) { var offsetContainer, offsetLastColumn; if ($ele.length > 0) { offsetContainer = $ele[0].getBoundingClientRect().right; offsetLastColumn = $ele.find('.swiper-slide:last-child')[0].getBoundingClientRect().right; if (offsetLastColumn - offsetContainer < 0) { $ele.next('.tips').css('display', 'none'); } else { $ele.next('.tips').css('display', 'block'); } } } //function isFlexSupport() { // var flex = document.createElement('p').style.flex, // webkitFlex = document.createElement('p').style.webkitFlex, // flexWrap = document.createElement('p').style.flexWrap; // // if ((flex === '' || webkitFlex === '') && flexWrap === '') { // return true; // } else { // return false; // } //} function wrapElements(selector, count) { var elArr = null; $(selector).each(function(idx, el) { elArr = $(selector).slice(idx, idx + count); if (elArr.length === count && idx % count === 0) { $(elArr).wrapAll($('<div class="js-wraper"></div>')); } }); } function search() { if (searching || end) { return; } searching = true; // alert($('#reference-swiper-container .swiper-wrapper').width()); loading.showLoadingMask(); $.ajax({ type: 'GET', url: introUrl, success: function(data) { $productDesc = $('#productDesc'); $productDesc.append(data); window.rePosFooter(); lazyLoad($productDesc.find('img.lazy')); //尺码信息左右滑动 sizeSwiper = new Swiper('#size-swiper-container',{ slidesPerView: 'auto' }); //模特试穿左右滑动 refSwiper = new Swiper('#reference-swiper-container',{ slidesPerView: 'auto' }); hiddenTips($('#size-swiper-container')); hiddenTips($('#reference-swiper-container')); //if (!isFlexSupport()) { // $('.detail .column').removeClass('column').addClass('oldbox'); //} wrapElements('.detail .column', 2); searching = false; end = true; loading.hideLoadingMask(); }, error: function() { tip.show('网络断开连接了~'); searching = false; loading.hideLoadingMask(); } }); } function scrollHandler() { if (!end || $(window).scrollTop() + winH >= $(document).height() - 50) { search(); } } //srcoll to load more $(window).scroll(function() { window.requestAnimationFrame(scrollHandler); }); }); define("js/product/detail/comments-consults", ["jquery","hammer"], function(require, exports, module){ /** * 商品详情 --评论和咨询tab * @author: Lynnic * @date: 2015/11/18 */ var $ = require("jquery"), tip = require("js/plugin/tip"), Hammer = require("hammer"); var commentsNum,consultsNum; var consultFooterEle = $('.consult-content-footer')[0], consultFooterHammer = consultFooterEle && new Hammer(consultFooterEle), navtabEle = document.getElementById('nav-tab'), navtabHammer = navtabEle && new Hammer(navtabEle), gotoConsultEle = document.getElementById('goto-consult'), gotoConsultHammer = gotoConsultEle && new Hammer(gotoConsultEle); (function() { consultsNum = $('#nav-tab .consults-num').html() - 0; commentsNum = $('#nav-tab .comments-num').html() - 0; $('#nav-tab li').each(function() { $(this).removeClass('focus'); }); $('#feedback-content .content').each(function() { $(this).addClass('hide'); }); if (0 !== commentsNum) { $('#nav-tab .comment-nav').addClass('focus'); $('#feedback-content .comment-content').removeClass('hide'); } else if (0 !== consultsNum) { $('#nav-tab .consult-nav').addClass('focus'); $('#feedback-content .consult-content').removeClass('hide'); } })(); if (navtabHammer) { navtabHammer.on('tap', function(e) { var $this = $(e.target).closest('li'); var index = $this.index(); if ($this.hasClass('comment-nav') && 0 === commentsNum) { tip.show('暂无商品评价'); } else { if (!$this.hasClass('focus')) { $('#nav-tab li').each(function() { $(this).removeClass('focus'); }); $('#feedback-content .content').each(function() { $(this).addClass('hide'); }); $this.addClass('focus'); $('#feedback-content .content:eq(' + index + ')').removeClass('hide'); } } }); } if (consultFooterHammer) { consultFooterHammer.on('tap', function() { location.href = $(consultFooterEle).data('href'); }); } if (gotoConsultHammer) { gotoConsultHammer.on('tap', function() { location.href = $(gotoConsultEle).data('href'); }); } //咨询页面固定header if ($('.goods-consults-page').length > 0) { $('#yoho-header').css('position', 'fixed').css('top', '0'); } }); define("js/product/recommend-for-you-product-desc", ["swiper","jquery","index"], function(require, exports, module){ /** * 为您优选 * @author: liangzhifeng<zhifeng.liang@yoho.cn> * @date: 2015/11/16 */ var Swiper = require("swiper"), $ = require("jquery"); var recommendSwiper, $recommendForYou = $('.recommend-for-you'), preferenceUrl = $('#preferenceUrl').val(); if (preferenceUrl) { $.get(preferenceUrl).then(function(html) { if (html.length < 5) { $recommendForYou.css('display', 'none'); } else { $recommendForYou.html(html).show(); if ($('#swiper-recommend').length) { recommendSwiper = new Swiper('#swiper-recommend', { slidesPerView: 'auto', grabCursor: true, slideElement: 'a', lazyLoading: true, watchSlidesVisibility: true }); } } window.rePosFooter(); }).fail(function() { $recommendForYou.hide(); }); } }); define("js/product/detail/like", ["jquery","hammer"], function(require, exports, module){ /** * 商品详情 --添加收藏 * @author: Lynnic * @date: 2015/11/24 */ var $ = require("jquery"), Hammer = require("hammer"), tip = require("js/plugin/tip"); var likeEle = document.getElementById('likeBtn'), likeHammer = likeEle && new Hammer(likeEle); var addToCartEle = document.getElementById('addtoCart'), addToCartHammer = addToCartEle && new Hammer(addToCartEle), productId = $('#productId').val(); if (likeHammer) { likeHammer.on('tap', function(e) { var opt, favorite; var $this = $(e.target); if ($this.hasClass('liked')) { opt = 'cancel'; favorite = 0; } else { opt = 'ok'; favorite = 1; } $.ajax({ type: 'POST', url: '/product/opt/favoriteProduct', data: { id: productId, opt: opt }, success: function(data) { if (data.code === 200) { $this.toggleClass('liked'); if ('cancel' === opt) { tip.show('取消收藏成功'); } else if ('ok' === opt) { tip.show('收藏成功'); } } else if (data.code === 400) { location.href = data.data;//未登录跳转登录页 } else { tip.show(data.message); } // 统计代码:用于统计用户加入或取消商品收藏的动作 if (window._yas) { window._yas.sendCustomInfo({ pd: productId, fa: favorite }); } }, error: function() { tip.show('网络断开连接了~'); } }); }); } if (addToCartHammer) { addToCartHammer.on('tap', function(e) { // 统计代码:用于统计用户加入购物车的动作 if (window._yas) { window._yas.sendCustomInfo({ pd: productId, by: 1 }); } }); } }); define("js/product/detail/consultform", ["jquery"], function(require, exports, module){ /** * 我要咨询提交页面 * @author: liangzhifeng<zhifeng.liang@yoho.cn> * @date: 2015/12/01 */ var $ = require("jquery"), tip = require("js/plugin/tip"), loading = require("js/plugin/loading"); var $consultForm = $('.consult-form'), $submit = $('#submit'), $content = $('#content'), productId = $('#product_id').val(), isSubmiting; $submit.on('touchend', function() { $content.blur(); $consultForm.submit(); return false; }).on('touchstart', function() { $(this).addClass('highlight'); }).on('touchend touchcancel', function() { $(this).removeClass('highlight'); }); $content.on('focus', function() { if ($content.val() === '请输入咨询内容') { $content.val(''); } }).on('blur', function() { if ($content.val() === '') { $content.val('请输入咨询内容'); } }); // 提交表单请求 $consultForm.on('submit', function() { var content; if (isSubmiting) { return false; } // 简单的表单校验 content = $content.val(); if (!content || content === '请输入咨询内容') { tip.show('咨询内容不能为空'); return false; } isSubmiting = true; loading.showLoadingMask(); $.ajax({ method: 'POST', url: '/product/detail/consultsubmit', data: { product_id: productId, content: content } }).then(function(res) { if ($.type(res) !== 'object') { res = {}; } if (res.code !== 200) { tip.show(res.message || '网络出了点问题~'); isSubmiting = false; loading.hideLoadingMask(); } else { tip.show('提交成功~'); setTimeout(function() { window.history.go(-1); }, 3000); } }).fail(function() { tip.show('网络出了点问题~'); isSubmiting = false; }); return false; }); }); define("js/product/newsale/hot-rank", ["jquery","swiper","lazyload","index"], function(require, exports, module){ var $ = require("jquery"), Swiper = require("swiper"), lazyLoad = require("lazyload"), loading = require("js/plugin/loading"); var page = 1, winH, listTop, navSwiper, notab = 0, sort = '', id = '', hotrankNav, noResult = '<p class="no-result">未找到相关搜索结果</p>'; require("js/product/suspend-cart"); function hotrank(page, sort, tabId, notab) { loading.showLoadingMask(); $.ajax({ type: 'GET', url: '/product/newsale/selectHotrank?' + sort, dataType: 'html', data: { page: page, tab_id: tabId, notab: notab }, success: function(data) { if (data === ' ') { if ($('.rank-main').length < 1 && $('.goods-nav').length < 1) { $('#hotRank').html(noResult); } else { if (page === 1) { hotrankNav = $('.goods-nav').prop('outerHTML'); $('#hotRank').html(hotrankNav + noResult); } } } else { $('.no-result').remove(); if (page === 1) { $('.rank-main').remove(); } $('#hotRank').append(data); } lazyLoad($('img.lazy')); $('.rank-main ul li:gt(9)').find('.item-content i').removeClass('top'); winH = $(window).height(); if ($('.rank-main').length !== 0) { $('#yoho-footer').css('position', 'static'); listTop = $('.rank-main').find('ul').offset().top; } else { $('#yoho-footer').css('position', 'fixed'); } navSwiper = new Swiper('.s-goods-nav', { grabCursor: true, slidesPerView: 'auto', slideElement: 'li' }); loading.hideLoadingMask(); } }); } function scrollHandler() { if (page === 2) { return; } if ($(window).scrollTop() + winH < listTop + $('#hotRank').height() - 100) { return; } page = 2; notab = 1; hotrank(page, sort, id, notab); } $(window).scroll(function() { window.requestAnimationFrame(scrollHandler); }); hotrank(page, sort, id, notab); $('#hotRank').on('touchend touchcancel', function(e) { var ev = ev || window.event; var target = ev.target || ev.srcElement; if (target.nodeName.toLowerCase() === 'span') { $('.s-goods-nav .nav-item').removeClass('active'); target.parentNode.className = 'active ' + target.parentNode.className; id = target.getAttribute('data-id') ? target.getAttribute('data-id') : ''; sort = target.getAttribute('data-sort') ? target.getAttribute('data-sort') : ''; page = 1; notab = 1; hotrank(page, sort, id, notab); } }); $('#hotRank').bind('contextmenu', function(e) { return false; }); $('#hotRank').on('touchstart', function(e) { var ev = ev || window.event; var target = ev.target || ev.srcElement; if (target.nodeName.toLowerCase() === 'span') { target.parentNode.className = 'bgActive ' + target.parentNode.className; } }).on('touchend touchcancel', function() { $('.s-goods-nav .nav-item').removeClass('bgActive'); }); }); define("js/me/entry", ["jquery","hammer","lazyload","handlebars","source-map","swiper","mlellipsis","index"], function(require, exports, module){ /** * 个人中心js打包入口文件 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/11/10 */ require("js/me/order"); require("js/me/order-detail"); require("js/me/fav"); require("js/me/suggest"); require("js/me/index"); require("js/me/coupons"); require("js/me/online-service"); require("js/me/address"); require("js/me/suggest"); require("js/me/browse-record"); require("js/me/address-act"); require("js/me/logistic"); require("js/me/pay"); require("js/me/personal-details"); }); define("js/me/order", ["jquery","hammer","lazyload","handlebars","source-map"], function(require, exports, module){ /** * 个人中心--我的订单 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/11/10 */ var $ = require("jquery"), Hammer = require("hammer"), lazyLoad = require("lazyload"); var $navLi = $('#order-nav > li'), $orderContainer = $('#order-container'); var $curContainer = $orderContainer.children('.orders:not(.hide)');//保存当前显示的order-container var winH = $(window).height(); var activeType = $navLi.filter('.active').data('type'); //当前active的项的index var order = { page: 0, end: false }; var inAjax = false; var loading = require("js/plugin/loading"); var dialog = require("js/me/dialog"); var orderHammer; //加载订单 function getOrders(option) { var opt = { type: activeType, page: order.page + 1 }; var show = option && !option.noLoadingMask; if (inAjax) { return; } inAjax = true; show && loading.showLoadingMask(); $.ajax({ type: 'GET', url: '/home/getOrders', data: opt, success: function(data) { var num; if (data !== ' ') { order.page = opt.page; if (opt.page === 1) { $curContainer.html(data); lazyLoad($curContainer.find('.lazy'), { try_again_css: 'order-failure' }); } else { num = $curContainer.children('.order').length; $curContainer.append(data); //lazyload lazyLoad($curContainer.children('.order:gt(' + (num - 1) + ')').find('.lazy'), { try_again_css: 'order-failure' }); } window.rePosFooter(); //重新计算底部位置 } else { order.end = true; } inAjax = false; show && loading.hideLoadingMask(); } }); } lazyLoad({ try_again_css: 'order-failure' }); //初始化导航 (function() { var liCount = $navLi.length; //默认4个导航项 if (liCount === 4) { return; } $navLi.width(100 / liCount + '%'); }()); loading.init($('body')); //满屏loading //点击订单区域跳转订单详情页 orderHammer = new Hammer(document.getElementById('order-container')); orderHammer.on('tap', function(e) { var $cur = $(e.target), $order, id, url; if ($cur.closest('.locHref').length > 0) { return; } $order = $cur.closest('.order'); id = $order.data('id'); if ($cur.closest('.del').length > 0) { //Order delete dialog.showDialog({ dialogText: '确定删除订单吗?', hasFooter: { leftBtnText: '取消', rightBtnText: '确定' } }, function() { $.ajax({ type: 'GET', url: '/home/delOrder', data: { id: id }, success: function(data) { if (data.code === 200) { dialog.showDialog({ dialogText: '删除订单成功', autoHide: true, fast: true }); //删除订单页面刷新 history.go(0); } }, error: function() { dialog.showDialog({ dialogText: '删除订单失败', autoHide: true, fast: true }); } }); }); } else if ($cur.closest('.cancel').length > 0) { //Order cancel dialog.showDialog({ dialogText: '确定取消订单吗?', hasFooter: { leftBtnText: '取消', rightBtnText: '确定' } }, function() { $.ajax({ type: 'GET', url: '/home/cancelOrder', data: { id: id }, success: function(data) { if (data.code === 200) { dialog.showDialog({ dialogText: '取消订单成功', autoHide: true, fast: true }); //取消订单页面刷新 history.go(0); } }, error: function() { dialog.showDialog({ dialogText: '取消订单失败', autoHide: true, fast: true }); } }); }); } else if ($cur.closest('.order-goods').length > 0) { //Location to order detail url = $order.data('href'); location.href = url; } }); function scrollHandler() { if (order.end === false && $(window).scrollTop() + winH > $(document).height() - 0.25 * $orderContainer.height()) { //下拉请求时不显示mask getOrders({ noLoadingMask: true }); } } //srcoll to load more $(window).scroll(function() { window.requestAnimationFrame(scrollHandler); }); //初始化请求第一页数据 getOrders(); }); define("js/me/dialog", ["jquery","handlebars","source-map","hammer"], function(require, exports, module){ /* * @Description: dialog * @Time: 2015/11/18 * @author: chenglong.wang */ var $ = require("jquery"), Handlebars = require("handlebars"), Hammer = require("hammer"); var $dialogWrapper, dialogTpl, dialogTemplate; dialogTpl = '<div id="dialog-wrapper" class="dialog-wrapper">' + '<div class="dialog-box">' + '{{# hasHeader}}' + '{{/ hasHeader}}' + '<div class="dialog-content">{{dialogText}}</div>' + '{{# hasFooter}}' + '<div class="dialog-footer">' + '{{# leftBtnText}}' + '<span class="dialog-left-btn">{{.}}</span>' + '{{/ leftBtnText}}' + '{{# rightBtnText}}' + '<span class="dialog-right-btn">{{.}}</span>' + '{{/ rightBtnText}}' + '</div>' + '{{/ hasFooter}}' + '</div>' + '</div>'; dialogTemplate = Handlebars.compile(dialogTpl); exports.showDialog = function(data, callback) { var dialogStr = dialogTemplate(data), $dialogBox, defaultHideDuraton, dialogWrapperHammer; $('.dialog-wrapper').remove(); $('body').append($(dialogStr)); $dialogBox = $('.dialog-box'); $dialogWrapper = $('.dialog-wrapper'); dialogWrapperHammer = new Hammer(document.getElementById('dialog-wrapper')); // 显示 if (data.fast) { $dialogWrapper.css({ display: 'block' }); } else { $dialogWrapper.fadeIn(); } $dialogBox.css({ top: '50%', marginTop: -($dialogBox.height() / 2) }); //隐藏 if (data.autoHide) { defaultHideDuraton = 1000; if (data.autoHide > 1) { defaultHideDuraton = data.autoHide; } setTimeout(function() { $dialogWrapper.fadeOut(); }, defaultHideDuraton); } dialogWrapperHammer.on('tap', function(event) { if ($(event.target).hasClass('dialog-left-btn')) { $dialogWrapper.fadeOut(); } else if ($(event.target).hasClass('dialog-right-btn')) { callback(); } }); }; }); define("js/me/order-detail", ["jquery","lazyload","hammer"], function(require, exports, module){ /** * 订单详情页 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/11/16 */ var $ = require("jquery"), lazyLoad = require("lazyload"), Hammer = require("hammer"); var orderId = $('#order-detail').data('id'); var optHammer; lazyLoad({ try_again_css: 'order-failure' }); //订单删除 optHammer = new Hammer(document.getElementsByClassName('opt')[0]); optHammer.on('tap', function(e) { var $cur = $(e.target); if ($cur.hasClass('btn-del')) { //删除订单 if (confirm('确定删除订单吗?')) { $.ajax({ type: 'GET', url: '/home/delOrder', data: { id: orderId } }); } } else if ($cur.hasClass('btn-cancel')) { //取消订单 if (confirm('确定取消订单吗?')) { $.ajax({ type: 'GET', url: '/home/cancelOrder', data: { id: orderId } }); } } }); }); define("js/me/fav", ["jquery","hammer","swiper","handlebars","source-map","index"], function(require, exports, module){ /** * 个人中心--收藏 * @author: chenglong<chenglong.wang@yoho.cn> * @date: 2015/11/12 */ var $ = require("jquery"), Hammer = require("hammer"), Swiper = require("swiper"); var diaLog = require("js/me/dialog"); var $navLi = $('#fav-tab > li'), $favContainer = $('.fav-content > .fav-type'), swiperObj = {}, favTabHammer, favContentHammer, $loadMore = $('.fav-load-more'), $brandLoadMore = $('.fav-brand-load-more'), winH = $(window).height(), footerH = $('#yoho-footer').height(), $favProductList = $('.fav-product-list'), $favBrandList = $('.fav-brand-swiper-wrapper'), pageId = 1, brandPageId = 1, //收藏品牌的当前页数 lockId = true, brandLockId = true, //收藏品牌是否可下拉加载更多 brandTab = false; //当前是否停留在收藏品牌页 function showFavTab(index) { $navLi.filter('.active').removeClass('active'); $navLi.eq(index).addClass('active'); $favContainer.filter('.show').removeClass('show'); $favContainer.eq(index).addClass('show'); } //初始化swiper function initSwiper(data) { var i, idStrReg = /container-(\d+)['"]{1}/gi, idReg = /\d+/, idArr = data.match(idStrReg), idArrLen = idArr.length, containerId; //$swiperList = $('.swiper-container'); for (i = 0; i < idArrLen; i++) { /*id = $swiperList.eq(i).attr('data-id'); if (!!swiperObj[id]) { swiperObj[id].destroy(true, true); }*/ containerId = idArr[i].match(idReg)[0]; swiperObj[containerId] = new Swiper('#swiper-container-' + containerId, { slidesPerView: 'auto', grabCursor: true, slideElement: 'li', wrapperClass: 'swiper-wrapper-' + containerId, lazyLoading: true, watchSlidesVisibility: true }); } } // 上拉加载更多 function loadData($parent, url, page) { if (url === 'favBrand') { brandLockId = true; } else { lockId = true; } $.ajax({ method: 'post', url: '/home/' + url, data: { page: page }, success: function(data) { if (url === 'favBrand') { $brandLoadMore.addClass('hide'); } else { $loadMore.addClass('hide'); } if (data === ' ') { $parent.closest('.fav-type').find('.fav-content-loading').addClass('hide'); $parent.closest('.fav-type').find('.fav-null-box').removeClass('hide'); } else if (data === 'end') { $parent.closest('.fav-type').find('.fav-load-background') .removeClass('fav-load-background').html('没有更多了'); } else if (data.length > 10) { $parent.append(data); $parent.closest('.fav-type').find('.fav-content-loading').remove(); if (url === 'favBrand') { initSwiper(data);//如果是收藏品牌需要初始化swiper brandLockId = false;//请求成功后解锁品牌收藏page++ } else { lockId = false;//请求成功后解锁商品收藏page++ } } window.rePosFooter(); } }); } // 如果从品牌收藏入口进入 if ($('#fav-tab').hasClass('brand-tab')) { showFavTab(1); loadData($favBrandList, 'favBrand', 1); brandTab = true; window.rePosFooter(); } else { showFavTab(0); loadData($favProductList, 'favProduct', 1); brandTab = false; window.rePosFooter(); } favTabHammer = new Hammer(document.getElementById('fav-tab')); favTabHammer.on('tap', function(e) { var $cur = $(e.target).closest('li'), index; if ($cur.length === 0 || $cur.hasClass('active')) { return; } index = $cur.index(); if (index === 0) { brandTab = false; if ($favProductList.find('li').length === 0 && $favProductList.closest('.fav-type').find('.fav-null-box').hasClass('hide')) { loadData($favProductList, 'favProduct', 1); } } else { brandTab = true; if ($favBrandList.find('div').length === 0 && $favBrandList.closest('.fav-type').find('.fav-null-box').hasClass('hide')) { loadData($favBrandList, 'favBrand', 1); } } showFavTab(index); window.rePosFooter(); }); //删除收藏的商品 favContentHammer = new Hammer(document.getElementById('fav-content')); favContentHammer.on('tap', function(e) { var id = ''; if (!$(e.target).hasClass('del-fav')) { return; } diaLog.showDialog({ dialogText: '您确定要取消收藏吗?', hasFooter: { leftBtnText: '取消', rightBtnText: '确定' } }, function() { id = $(e.target).closest('li').attr('data-id'); $.ajax({ method: 'post', url: '/home/favoriteDel', data: { id: id } }).then(function(data) { if (data.code === 200) { diaLog.showDialog({ autoHide: true, fast: true, dialogText: '已经取消收藏' }); $(e.target).closest('li').remove(); } else if (data.code === 400) { diaLog.showDialog({ autoHide: true, fast: true, dialogText: data.message }); } else { diaLog.showDialog({ autoHide: true, fast: true, dialogText: '取消收藏失败' }); } }).fail(function() { //TODO diaLog.showDialog({ autoHide: true, dialogText: '网络错误~' }); }); }); }); function scrollHandler() { //距离底部未1/4列表高度+底部高度的时候加载更多 if ($(window).scrollTop() + winH >= $(document).height() - 0.25 * $favBrandList.height() - footerH) { if (brandTab) { $brandLoadMore.filter('.hide').removeClass('hide'); if (!brandLockId) { brandPageId++; loadData($favBrandList, 'favBrand', brandPageId); } } else { $loadMore.filter('.hide').removeClass('hide'); if (!lockId) { pageId++; loadData($favProductList, 'favProduct', pageId); } } } } //srcoll to load more $(window).scroll(scrollHandler); $(document).on('touchend', '.swiper-header', function() { var url = $(this).find('.fav-more').attr('href'); window.location.href = url; }); }); define("js/me/suggest", ["jquery","hammer","lazyload","handlebars","source-map"], function(require, exports, module){ /** * 个人中心--意见反馈 * @author: chenglong<chenglong.wang@yoho.cn> * @date: 2015/11/12 */ var $ = require("jquery"), Hammer = require("hammer"), lazyLoad = require("lazyload"), Handlebars = require("handlebars"); var diaLog = require("js/me/dialog"); var $uploadImgList = $('.upload-img-list'), headerNavHammer, formHammer, imgTpl, imgTemplate, $likeBtn = $('.suggest-item .like-btn'), $disLikeBtn = $('.suggest-item .dislike-btn'), $imgAdd = $('.img-add'), imgStr = '', uploadImgNum = 0; require("js/me/jquery.uploadifive"); imgTpl = '{{# imgList}}' + '<li>' + '{{# imgUrl}}<img src="{{.}}" />' + '<span class="upload-img-remove"></span>{{/ imgUrl}}' + '</li>' + '{{/ imgList}}'; imgTemplate = Handlebars.compile(imgTpl); $('#upload-img').uploadifive({ auto: true, fileType: 'image*/*', uploadScript: '/home/suggestimgUpload', fileObjName: 'fileData', fileSizeLimit: 300, height: '100%', width: '100%', multi: false, onAddQueueItem: function(files) { //TODO $uploadImgList.html(imgTemplate({ imgList: true })); }, onUploadComplete: function(file, data) { $uploadImgList.html(''); imgStr = JSON.parse(data).imgList[0].imgRelUrl; $uploadImgList.html(imgTemplate(JSON.parse(data))); $imgAdd.hide(); uploadImgNum++; } }); lazyLoad(); headerNavHammer = new Hammer(document.getElementById('yoho-header')); headerNavHammer.on('tap', function(e) { var suggestText = $('#suggest-textarea').val(), textReg = /\S+/; if ($(e.target).hasClass('nav-btn')) { if (!textReg.test(suggestText)) { diaLog.showDialog({ autoHide: true, dialogText: '意见不能为空' }); return; } $.ajax({ method: 'post', url: '/home/savesuggest', data: { content: suggestText, image: imgStr } }).then(function(data) { if (data.code === 200) { diaLog.showDialog({ autoHide: true, dialogText: '提交成功' }); setTimeout(function() { location.pathname = 'home/suggest'; }, 2000); } else { diaLog.showDialog({ autoHide: true, dialogText: '提交失败~' }); } }).fail(function() { diaLog.showDialog({ autoHide: true, dialogText: '网络错误~' }); }); } }); if (document.getElementById('img-form') !== null) { formHammer = new Hammer(document.getElementById('img-form')); formHammer.on('tap', function(e) { if ($(e.target).hasClass('upload-img-remove')) { $uploadImgList.html(''); imgStr = ''; uploadImgNum--; setTimeout(function() { $imgAdd.show(); }, 50); } }); } // 点赞与取消点赞 $likeBtn.bind('click', function() { var id = $(this).closest('.suggest-item').attr('data-id'), $that = $(this); $.ajax({ method: 'post', url: '/home/upAndDown', data: { suggest_id: id, reliable: 1 } }).then(function(data) { if (data.code === 200) { $that.closest('.suggest-type').removeClass('show'); $that.closest('.suggest-item').find('.suggest-good').addClass('show'); } }).fail(function(data) { //TODO diaLog.showDialog({ autoHide: true, dialogText: '网络错误~' }); }); }); $disLikeBtn.bind('click', function() { var id = $(this).closest('.suggest-item').attr('data-id'), $that = $(this); $.ajax({ method: 'post', url: '/home/upAndDown', data: { suggest_id: id, reliable: 2 } }).then(function(data) { if (data.code === 200) { $that.closest('.suggest-type').removeClass('show'); $that.closest('.suggest-item').find('.suggest-bad').addClass('show'); } }).fail(function(data) { //TODO diaLog.showDialog({ autoHide: true, dialogText: '网络错误~' }); }); }); }); define("js/me/jquery.uploadifive", ["jquery"], function(require, exports, module){ /* UploadiFive 1.2.2 Copyright (c) 2012 Reactive Apps, Ronnie Garcia Released under the UploadiFive Standard License <http://www.uploadify.com/uploadifive-standard-license> */ var jQuery = require("jquery"); ;(function($) { var methods = { init : function(options) { return this.each(function() { // Create a reference to the jQuery DOM object var $this = $(this); $this.data('uploadifive', { inputs : {}, // The object that contains all the file inputs inputCount : 0, // The total number of file inputs created fileID : 0, queue : { count : 0, // Total number of files in the queue selected : 0, // Number of files selected in the last select operation replaced : 0, // Number of files replaced in the last select operation errors : 0, // Number of files that returned an error in the last select operation queued : 0, // Number of files added to the queue in the last select operation cancelled : 0 // Total number of files that have been cancelled or removed from the queue }, uploads : { current : 0, // Number of files currently being uploaded attempts : 0, // Number of file uploads attempted in the last upload operation successful : 0, // Number of files successfully uploaded in the last upload operation errors : 0, // Number of files returning errors in the last upload operation count : 0 // Total number of files uploaded successfully } }); var $data = $this.data('uploadifive'); // Set the default options var settings = $data.settings = $.extend({ 'auto' : true, // Automatically upload a file when it's added to the queue 'buttonClass' : false, // A class to add to the UploadiFive button 'buttonText' : 'Select Files', // The text that appears on the UploadiFive button 'checkScript' : false, // Path to the script that checks for existing file names 'dnd' : true, // Allow drag and drop into the queue 'dropTarget' : false, // Selector for the drop target 'fileObjName' : 'Filedata', // The name of the file object to use in your server-side script 'fileSizeLimit' : 0, // Maximum allowed size of files to upload 'fileType' : false, // Type of files allowed (image, etc), separate with a pipe character | 'formData' : {}, // Additional data to send to the upload script 'height' : 30, // The height of the button 'itemTemplate' : false, // The HTML markup for the item in the queue 'method' : 'post', // The method to use when submitting the upload 'multi' : true, // Set to true to allow multiple file selections 'overrideEvents' : [], // An array of events to override 'queueID' : false, // The ID of the file queue 'queueSizeLimit' : 0, // The maximum number of files that can be in the queue 'removeCompleted' : false, // Set to true to remove files that have completed uploading 'simUploadLimit' : 0, // The maximum number of files to upload at once 'truncateLength' : 0, // The length to truncate the file names to 'uploadLimit' : 0, // The maximum number of files you can upload 'uploadScript' : 'uploadifive.php', // The path to the upload script 'width' : 100 // The width of the button /* // Events 'onAddQueueItem' : function(file) {}, // Triggered for each file that is added to the queue 'onCancel' : function(file) {}, // Triggered when a file is cancelled or removed from the queue 'onCheck' : function(file, exists) {}, // Triggered when the server is checked for an existing file 'onClearQueue' : function(queue) {}, // Triggered during the clearQueue function 'onDestroy' : function() {} // Triggered during the destroy function 'onDrop' : function(files, numberOfFilesDropped) {}, // Triggered when files are dropped into the file queue 'onError' : function(file, fileType, data) {}, // Triggered when an error occurs 'onFallback' : function() {}, // Triggered if the HTML5 File API is not supported by the browser 'onInit' : function() {}, // Triggered when UploadiFive if initialized 'onQueueComplete' : function() {}, // Triggered once when an upload queue is done 'onProgress' : function(file, event) {}, // Triggered during each progress update of an upload 'onSelect' : function() {}, // Triggered once when files are selected from a dialog box 'onUpload' : function(file) {}, // Triggered when an upload queue is started 'onUploadComplete' : function(file, data) {}, // Triggered when a file is successfully uploaded 'onUploadFile' : function(file) {}, // Triggered for each file being uploaded */ }, options); // Calculate the file size limit if (isNaN(settings.fileSizeLimit)) { var fileSizeLimitBytes = parseInt(settings.fileSizeLimit) * 1.024 if (settings.fileSizeLimit.indexOf('KB') > -1) { settings.fileSizeLimit = fileSizeLimitBytes * 1000; } else if (settings.fileSizeLimit.indexOf('MB') > -1) { settings.fileSizeLimit = fileSizeLimitBytes * 1000000; } else if (settings.fileSizeLimit.indexOf('GB') > -1) { settings.fileSizeLimit = fileSizeLimitBytes * 1000000000; } } else { settings.fileSizeLimit = settings.fileSizeLimit * 1024; } // Create a template for a file input $data.inputTemplate = $('<input type="file">') .css({ 'font-size' : settings.height + 'px', 'opacity' : 0, 'position' : 'absolute', 'right' : '-3px', 'top' : '-3px', 'z-index' : 999 }); // Create a new input $data.createInput = function() { // Create a clone of the file input var input = $data.inputTemplate.clone(); // Create a unique name for the input item var inputName = input.name = 'input' + $data.inputCount++; // Set the multiple attribute if (settings.multi) { input.attr('multiple', true); } // Set the accept attribute on the input if (settings.fileType) { input.attr('accept', settings.fileType); } // Set the onchange event for the input input.bind('change', function() { $data.queue.selected = 0; $data.queue.replaced = 0; $data.queue.errors = 0; $data.queue.queued = 0; // Add a queue item to the queue for each file var limit = this.files.length; $data.queue.selected = limit; if (($data.queue.count + limit) > settings.queueSizeLimit && settings.queueSizeLimit !== 0) { if ($.inArray('onError', settings.overrideEvents) < 0) { alert('The maximum number of queue items has been reached (' + settings.queueSizeLimit + '). Please select fewer files.'); } // Trigger the error event if (typeof settings.onError === 'function') { settings.onError.call($this, 'QUEUE_LIMIT_EXCEEDED'); } } else { for (var n = 0; n < limit; n++) { file = this.files[n]; $data.addQueueItem(file); } $data.inputs[inputName] = this; $data.createInput(); } // Upload the file if auto-uploads are enabled if (settings.auto) { methods.upload.call($this); } // Trigger the select event if (typeof settings.onSelect === 'function') { settings.onSelect.call($this, $data.queue); } }); // Hide the existing current item and add the new one if ($data.currentInput) { $data.currentInput.hide(); } $data.button.append(input); $data.currentInput = input; } // Remove an input $data.destroyInput = function(key) { $($data.inputs[key]).remove(); delete $data.inputs[key]; $data.inputCount--; } // Drop a file into the queue $data.drop = function(e) { $data.queue.selected = 0; $data.queue.replaced = 0; $data.queue.errors = 0; $data.queue.queued = 0; var fileData = e.dataTransfer; var inputName = fileData.name = 'input' + $data.inputCount++; // Add a queue item to the queue for each file var limit = fileData.files.length; $data.queue.selected = limit; if (($data.queue.count + limit) > settings.queueSizeLimit && settings.queueSizeLimit !== 0) { // Check if the queueSizeLimit was reached if ($.inArray('onError', settings.overrideEvents) < 0) { alert('The maximum number of queue items has been reached (' + settings.queueSizeLimit + '). Please select fewer files.'); } // Trigger the onError event if (typeof settings.onError === 'function') { settings.onError.call($this, 'QUEUE_LIMIT_EXCEEDED'); } } else { // Add a queue item for each file for (var n = 0; n < limit; n++) { file = fileData.files[n]; $data.addQueueItem(file); } // Save the data to the inputs object $data.inputs[inputName] = fileData; } // Upload the file if auto-uploads are enabled if (settings.auto) { methods.upload.call($this); } // Trigger the onDrop event if (typeof settings.onDrop === 'function') { settings.onDrop.call($this, fileData.files, fileData.files.length); } // Stop FireFox from opening the dropped file(s) e.preventDefault(); e.stopPropagation(); } // Check if a filename exists in the queue $data.fileExistsInQueue = function(file) { for (var key in $data.inputs) { input = $data.inputs[key]; limit = input.files.length; for (var n = 0; n < limit; n++) { existingFile = input.files[n]; // Check if the filename matches if (existingFile.name == file.name && !existingFile.complete) { return true; } } } return false; } // Remove an existing file in the queue $data.removeExistingFile = function(file) { for (var key in $data.inputs) { input = $data.inputs[key]; limit = input.files.length; for (var n = 0; n < limit; n++) { existingFile = input.files[n]; // Check if the filename matches if (existingFile.name == file.name && !existingFile.complete) { $data.queue.replaced++; methods.cancel.call($this, existingFile, true); } } } } // Create the file item template if (settings.itemTemplate == false) { $data.queueItem = $('<div class="uploadifive-queue-item">\ <a class="close" href="#">X</a>\ <div><span class="filename"></span><span class="fileinfo"></span></div>\ <div class="progress">\ <div class="progress-bar"></div>\ </div>\ </div>'); } else { $data.queueItem = $(settings.itemTemplate); } // Add an item to the queue $data.addQueueItem = function(file) { if ($.inArray('onAddQueueItem', settings.overrideEvents) < 0) { // Check if the filename already exists in the queue $data.removeExistingFile(file); // Create a clone of the queue item template file.queueItem = $data.queueItem.clone(); // Add an ID to the queue item file.queueItem.attr('id', settings.id + '-file-' + $data.fileID++); // Bind the close event to the close button file.queueItem.find('.close').bind('click', function() { methods.cancel.call($this, file); return false; }); var fileName = file.name; if (fileName.length > settings.truncateLength && settings.truncateLength != 0) { fileName = fileName.substring(0, settings.truncateLength) + '...'; } file.queueItem.find('.filename').html(fileName); // Add a reference to the file file.queueItem.data('file', file); $data.queueEl.append(file.queueItem); } // Trigger the addQueueItem event if (typeof settings.onAddQueueItem === 'function') { settings.onAddQueueItem.call($this, file); } // Check the filesize if (file.size > settings.fileSizeLimit && settings.fileSizeLimit != 0) { $data.error('FILE_SIZE_LIMIT_EXCEEDED', file); } else { $data.queue.queued++; $data.queue.count++; } } // Remove an item from the queue $data.removeQueueItem = function(file, instant, delay) { // Set the default delay if (!delay) delay = 0; var fadeTime = instant ? 0 : 500; if (file.queueItem) { if (file.queueItem.find('.fileinfo').html() != ' - Completed') { file.queueItem.find('.fileinfo').html(' - Cancelled'); } file.queueItem.find('.progress-bar').width(0); file.queueItem.delay(delay).fadeOut(fadeTime, function() { $(this).remove(); }); delete file.queueItem; $data.queue.count--; } } // Count the number of files that need to be uploaded $data.filesToUpload = function() { var filesToUpload = 0; for (var key in $data.inputs) { input = $data.inputs[key]; limit = input.files.length; for (var n = 0; n < limit; n++) { file = input.files[n]; if (!file.skip && !file.complete) { filesToUpload++; } } } return filesToUpload; } // Check if a file exists $data.checkExists = function(file) { if ($.inArray('onCheck', settings.overrideEvents) < 0) { // This request needs to be synchronous $.ajaxSetup({ 'async' : false }); // Send the filename to the check script var checkData = $.extend(settings.formData, {filename: file.name}); $.post(settings.checkScript, checkData, function(fileExists) { file.exists = parseInt(fileExists); }); if (file.exists) { if (!confirm('A file named ' + file.name + ' already exists in the upload folder.\nWould you like to replace it?')) { // If not replacing the file, cancel the upload methods.cancel.call($this, file); return true; } } } // Trigger the check event if (typeof settings.onCheck === 'function') { settings.onCheck.call($this, file, file.exists); } return false; } // Upload a single file $data.uploadFile = function(file, uploadAll) { if (!file.skip && !file.complete && !file.uploading) { file.uploading = true; $data.uploads.current++; $data.uploads.attempted++; // Create a new AJAX request xhr = file.xhr = new XMLHttpRequest(); // Start the upload // Use the faster FormData if it exists if (typeof FormData === 'function' || typeof FormData === 'object') { // Create a new FormData object var formData = new FormData(); // Add the form data formData.append(settings.fileObjName, file); // Add the rest of the formData for (i in settings.formData) { formData.append(i, settings.formData[i]); } // Open the AJAX call xhr.open(settings.method, settings.uploadScript, true); // On progress function xhr.upload.addEventListener('progress', function(e) { if (e.lengthComputable) { $data.progress(e, file); } }, false); // On complete function xhr.addEventListener('load', function(e) { if (this.readyState == 4) { file.uploading = false; if (this.status == 200) { if (file.xhr.responseText !== 'Invalid file type.') { $data.uploadComplete(e, file, uploadAll); } else { $data.error(file.xhr.responseText, file, uploadAll); } } else if (this.status == 404) { $data.error('404_FILE_NOT_FOUND', file, uploadAll); } else if (this.status == 403) { $data.error('403_FORBIDDEN', file, uploadAll); } else { $data.error('Unknown Error', file, uploadAll); } } }); // Send the form data (multipart/form-data) xhr.send(formData); } else { // Send as binary var reader = new FileReader(); reader.onload = function(e) { // Set some file builder variables var boundary = '-------------------------' + (new Date).getTime(), dashes = '--', eol = '\r\n', binFile = ''; // Build an RFC2388 String binFile += dashes + boundary + eol; // Generate the headers binFile += 'Content-Disposition: form-data; name="' + settings.fileObjName + '"'; if (file.name) { binFile += '; filename="' + file.name + '"'; } binFile += eol; binFile += 'Content-Type: application/octet-stream' + eol + eol; binFile += e.target.result + eol; for (key in settings.formData) { binFile += dashes + boundary + eol; binFile += 'Content-Disposition: form-data; name="' + key + '"' + eol + eol; binFile += settings.formData[key] + eol; } binFile += dashes + boundary + dashes + eol; // On progress function xhr.upload.addEventListener('progress', function(e) { $data.progress(e, file); }, false); // On complete function xhr.addEventListener('load', function(e) { file.uploading = false; var status = this.status; if (status == 404) { $data.error('404_FILE_NOT_FOUND', file, uploadAll); } else { if (file.xhr.responseText != 'Invalid file type.') { $data.uploadComplete(e, file, uploadAll); } else { $data.error(file.xhr.responseText, file, uploadAll); } } }, false); // Open the ajax request var url = settings.uploadScript; if (settings.method == 'get') { var params = $(settings.formData).param(); url += params; } xhr.open(settings.method, settings.uploadScript, true); xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary); // Trigger the uploadFile event if (typeof settings.onUploadFile === 'function') { settings.onUploadFile.call($this, file); } // Send the file for upload xhr.sendAsBinary(binFile); } reader.readAsBinaryString(file); } } } // Update a file upload's progress $data.progress = function(e, file) { if ($.inArray('onProgress', settings.overrideEvents) < 0) { if (e.lengthComputable) { var percent = Math.round((e.loaded / e.total) * 100); } file.queueItem.find('.fileinfo').html(' - ' + percent + '%'); file.queueItem.find('.progress-bar').css('width', percent + '%'); } // Trigger the progress event if (typeof settings.onProgress === 'function') { settings.onProgress.call($this, file, e); } } // Trigger an error $data.error = function(errorType, file, uploadAll) { if ($.inArray('onError', settings.overrideEvents) < 0) { // Get the error message switch(errorType) { case '404_FILE_NOT_FOUND': errorMsg = '404 Error'; break; case '403_FORBIDDEN': errorMsg = '403 Forbidden'; break; case 'FORBIDDEN_FILE_TYPE': errorMsg = 'Forbidden File Type'; break; case 'FILE_SIZE_LIMIT_EXCEEDED': errorMsg = 'File Too Large'; break; default: errorMsg = 'Unknown Error'; break; } // Add the error class to the queue item file.queueItem.addClass('error') // Output the error in the queue item .find('.fileinfo').html(' - ' + errorMsg); // Hide the file.queueItem.find('.progress').remove(); } // Trigger the error event if (typeof settings.onError === 'function') { settings.onError.call($this, errorType, file); } file.skip = true; if (errorType == '404_FILE_NOT_FOUND') { $data.uploads.errors++; } else { $data.queue.errors++; } if (uploadAll) { methods.upload.call($this, null, true); } } // Trigger when a single file upload is complete $data.uploadComplete = function(e, file, uploadAll) { if ($.inArray('onUploadComplete', settings.overrideEvents) < 0) { file.queueItem.find('.progress-bar').css('width', '100%'); file.queueItem.find('.fileinfo').html(' - Completed'); file.queueItem.find('.progress').slideUp(250); file.queueItem.addClass('complete'); } // Trigger the complete event if (typeof settings.onUploadComplete === 'function') { settings.onUploadComplete.call($this, file, file.xhr.responseText); } if (settings.removeCompleted) { setTimeout(function() { methods.cancel.call($this, file); }, 3000); } file.complete = true; $data.uploads.successful++; $data.uploads.count++; $data.uploads.current--; delete file.xhr; if (uploadAll) { methods.upload.call($this, null, true); } } // Trigger when all the files are done uploading $data.queueComplete = function() { // Trigger the queueComplete event if (typeof settings.onQueueComplete === 'function') { settings.onQueueComplete.call($this, $data.uploads); } } // ---------------------- // Initialize UploadiFive // ---------------------- // Check if HTML5 is available if (window.File && window.FileList && window.Blob && (window.FileReader || window.FormData)) { // Assign an ID to the object settings.id = 'uploadifive-' + $this.attr('id'); // Wrap the file input in a div with overflow set to hidden $data.button = $('<div id="' + settings.id + '" class="uploadifive-button">' + settings.buttonText + '</div>'); if (settings.buttonClass) $data.button.addClass(settings.buttonClass); // Style the button wrapper $data.button.css({ 'height' : settings.height, 'line-height' : settings.height + 'px', 'overflow' : 'hidden', 'position' : 'relative', 'text-align' : 'center', 'width' : settings.width }); // Insert the button above the file input $this.before($data.button) // Add the file input to the button .appendTo($data.button) // Modify the styles of the file input .hide(); // Create a new input $data.createInput.call($this); // Create the queue container if (!settings.queueID) { settings.queueID = settings.id + '-queue'; $data.queueEl = $('<div id="' + settings.queueID + '" class="uploadifive-queue" />'); $data.button.after($data.queueEl); } else { $data.queueEl = $('#' + settings.queueID); } // Add drag and drop functionality if (settings.dnd) { var $dropTarget = settings.dropTarget ? $(settings.dropTarget) : $data.queueEl.get(0); $dropTarget.addEventListener('dragleave', function(e) { // Stop FireFox from opening the dropped file(s) e.preventDefault(); e.stopPropagation(); }, false); $dropTarget.addEventListener('dragenter', function(e) { // Stop FireFox from opening the dropped file(s) e.preventDefault(); e.stopPropagation(); }, false); $dropTarget.addEventListener('dragover', function(e) { // Stop FireFox from opening the dropped file(s) e.preventDefault(); e.stopPropagation(); }, false); $dropTarget.addEventListener('drop', $data.drop, false); } // Send as binary workaround for Chrome if (!XMLHttpRequest.prototype.sendAsBinary) { XMLHttpRequest.prototype.sendAsBinary = function(datastr) { function byteValue(x) { return x.charCodeAt(0) & 0xff; } var ords = Array.prototype.map.call(datastr, byteValue); var ui8a = new Uint8Array(ords); this.send(ui8a.buffer); } } // Trigger the oninit event if (typeof settings.onInit === 'function') { settings.onInit.call($this); } } else { // Trigger the fallback event if (typeof settings.onFallback === 'function') { settings.onFallback.call($this); } return false; } }); }, // Write some data to the console debug : function() { return this.each(function() { console.log($(this).data('uploadifive')); }); }, // Clear all the items from the queue clearQueue : function() { this.each(function() { var $this = $(this), $data = $this.data('uploadifive'), settings = $data.settings; for (var key in $data.inputs) { input = $data.inputs[key]; limit = input.files.length; for (i = 0; i < limit; i++) { file = input.files[i]; methods.cancel.call($this, file); } } // Trigger the onClearQueue event if (typeof settings.onClearQueue === 'function') { settings.onClearQueue.call($this, $('#' + $data.settings.queueID)); } }); }, // Cancel a file upload in progress or remove a file from the queue cancel : function(file, fast) { this.each(function() { var $this = $(this), $data = $this.data('uploadifive'), settings = $data.settings; // If user passed a queue item ID instead of file... if (typeof file === 'string') { if (!isNaN(file)) { fileID = 'uploadifive-' + $(this).attr('id') + '-file-' + file; } file = $('#' + fileID).data('file'); } file.skip = true; $data.filesCancelled++; if (file.uploading) { $data.uploads.current--; file.uploading = false; file.xhr.abort(); delete file.xhr; methods.upload.call($this); } if ($.inArray('onCancel', settings.overrideEvents) < 0) { $data.removeQueueItem(file, fast); } // Trigger the cancel event if (typeof settings.onCancel === 'function') { settings.onCancel.call($this, file); } }); }, // Upload the files in the queue upload : function(file, keepVars) { this.each(function() { var $this = $(this), $data = $this.data('uploadifive'), settings = $data.settings; if (file) { $data.uploadFile.call($this, file); } else { // Check if the upload limit was reached if (($data.uploads.count + $data.uploads.current) < settings.uploadLimit || settings.uploadLimit == 0) { if (!keepVars) { $data.uploads.attempted = 0; $data.uploads.successsful = 0; $data.uploads.errors = 0; var filesToUpload = $data.filesToUpload(); // Trigger the onUpload event if (typeof settings.onUpload === 'function') { settings.onUpload.call($this, filesToUpload); } } // Loop through the files $('#' + settings.queueID).find('.uploadifive-queue-item').not('.error, .complete').each(function() { _file = $(this).data('file'); // Check if the simUpload limit was reached if (($data.uploads.current >= settings.simUploadLimit && settings.simUploadLimit !== 0) || ($data.uploads.current >= settings.uploadLimit && settings.uploadLimit !== 0) || ($data.uploads.count >= settings.uploadLimit && settings.uploadLimit !== 0)) { return false; } if (settings.checkScript) { // Let the loop know that we're already processing this file _file.checking = true; skipFile = $data.checkExists(_file); _file.checking = false; if (!skipFile) { $data.uploadFile(_file, true); } } else { $data.uploadFile(_file, true); } }); if ($('#' + settings.queueID).find('.uploadifive-queue-item').not('.error, .complete').size() == 0) { $data.queueComplete(); } } else { if ($data.uploads.current == 0) { if ($.inArray('onError', settings.overrideEvents) < 0) { if ($data.filesToUpload() > 0 && settings.uploadLimit != 0) { alert('The maximum upload limit has been reached.'); } } // Trigger the onError event if (typeof settings.onError === 'function') { settings.onError.call($this, 'UPLOAD_LIMIT_EXCEEDED', $data.filesToUpload()); } } } } }); }, // Destroy an instance of UploadiFive destroy : function() { this.each(function() { var $this = $(this), $data = $this.data('uploadifive'), settings = $data.settings; // Clear the queue methods.clearQueue.call($this); // Destroy the queue if it was created if (!settings.queueID) $('#' + settings.queueID).remove(); // Remove extra inputs $this.siblings('input').remove(); // Show the original file input $this.show() // Move the file input out of the button .insertBefore($data.button); // Delete the button $data.button.remove(); // Trigger the destroy event if (typeof settings.onDestroy === 'function') { settings.onDestroy.call($this); } }); } } $.fn.uploadifive = function(method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('The method ' + method + ' does not exist in $.uploadify'); } } })(jQuery); }); define("js/me/index", ["jquery","swiper","index"], function(require, exports, module){ /** * 个人中心首页 * @author: bikai<kai.bi@yoho.cn> * @date: 2015/11/12 */ var $ = require("jquery"); var $userAvatar = $('.user-avatar'), $listItem = $('.list-item'); var myImage = new Image(), avatar; require("js/product/recommend-for-you"); require("js/product/suspend-cart"); // 部分老用户没有头像,显示默认头像 avatar = $userAvatar.data('avatar'); myImage.src = avatar; myImage.onload = function() { $userAvatar.css('background-image', 'url(' + avatar + ')'); }; $('.yoho-page').on('touchstart', '.list-item, .type-item, .order-title', function() { $listItem.removeClass('highlight'); $(this).addClass('highlight'); }).on('touchend touchcancel', '.list-item, .type-item, .order-title', function() { $(this).removeClass('highlight'); }); }); define("js/product/recommend-for-you", ["swiper","jquery","index"], function(require, exports, module){ /** * 为您优选 * @author: bikai<kai.bi@yoho.cn> * @date: 2015/11/16 */ var Swiper = require("swiper"), $ = require("jquery"); var recommendSwiper, $recommendForYou = $('.recommend-for-you'); $.get('/home/preference').then(function(html) { $recommendForYou.html(html).show(); if ($('#swiper-recommend').length) { recommendSwiper = new Swiper('#swiper-recommend', { slidesPerView: 'auto', grabCursor: true, slideElement: 'a', lazyLoading: true, watchSlidesVisibility: true }); } }).fail(function() { $recommendForYou.hide(); }); }); define("js/me/coupons", ["jquery","hammer","mlellipsis"], function(require, exports, module){ var $ = require("jquery"), Hammer = require("hammer"), ellipsis = require("mlellipsis"), loading = require("js/plugin/loading"); var employ, statu = 0, page = 1; ellipsis.init(); function couponAJAX(statu, page) { loading.showLoadingMask(); $.ajax({ type: 'POST', url: '/home/couponData', dataType: 'html', data: { status: statu, page: page }, success: function(data) { $('#employ').append(data); window.rePosFooter(); loading.hideLoadingMask(); } }); } $('.yoho-footer').css('border-top', '1px solid #e0e0e0'); $('.employ span').each(function(index) { employ = new Hammer($('.employ span')[index]); employ.on('tap', function(e) { $('.employ span').removeClass('active').eq(index).addClass('active'); $('#employ').html(' '); statu = index; page = 1; couponAJAX(statu, page); window.rePosFooter(); }); }); $(window).scroll(function() { if ($(window).scrollTop() + $(window).height() > $('body').height() - 1) { page++; couponAJAX(statu, page); return; } }); couponAJAX(statu, page); }); define("js/me/online-service", ["jquery"], function(require, exports, module){ /** * 在线客服 * @author: bikai<kai.bi@yoho.cn> * @date: 2015/11/16 */ var $ = require("jquery"); var $questionTab = $('.question-tab .tab-item'); $questionTab.on('touchend', function() { var clickTab = $(this).data('tab'); clickTab = '[data-tab-name="' + clickTab + '"]'; $questionTab.removeClass('current'); $(this).addClass('current'); $('.question-list').removeClass('current'); $(clickTab).addClass('current'); }); $('.yoho-page').on('touchstart', '.connect-item, .question-item', function() { $(this).siblings().removeClass('highlight'); $(this).addClass('highlight'); }).on('touchend touchcancel', '.connect-item, .question-item', function() { $(this).removeClass('highlight'); }); }); define("js/me/address", ["jquery"], function(require, exports, module){ /** * 地址管理 * @author: bikai<kai.bi@yoho.cn> * @date: 2015/11/17 */ var $ = require("jquery"), tip = require("js/plugin/tip"), loading = require("js/plugin/loading"); var $action = $('.action'), $addAddress = $('.add-address'), $footer = $('#yoho-footer'), $confim = $('.confim-mask'), $pageWrap = $('.page-wrap'), $addressItem = $('.address-item'), deleteId; $pageWrap.first().css('min-height', function() { return $(window).height() - $('#yoho-header').height() - $footer.height(); }); window.rePosFooter(); $confim.on('touchend', '.cancel', function(e) { deleteId = null; $confim.fadeOut(); return false; }).on('touchend', '.confim', function() { loading.showLoadingMask(); $confim.fadeOut(); $.ajax({ method: 'POST', url: '/home/delAddress', data: { id: deleteId } }).then(function(res) { if ($.type(res) !== 'object') { res = {}; } if (res.code !== 200) { tip.show(res.message || '网络出了点问题~'); loading.hideLoadingMask(); } else { window.location.reload(); } }).fail(function() { tip.show('网络出了点问题~'); loading.hideLoadingMask(); }).always(function() { deleteId = null; }); return false; }); // 添加地址 if ($addressItem.length < 5) { $addAddress.attr('href', $addAddress.data('href')); } $addAddress.on('touchend', function() { if ($addressItem.length >= 5) { tip.show('您最多添加5个收货地址'); return false; } }); // 删除 $action.on('touchend', '.del', function() { deleteId = $(this).data('id'); $confim.fadeIn(); }); }); define("js/me/browse-record", ["jquery","lazyload","handlebars","source-map","hammer"], function(require, exports, module){ /** * 浏览记录 * @author: xuqi<qi.xu@yoho.cn> * @date: 2015/11/28 */ var $ = require("jquery"); var lazyLoad = require("lazyload"); var load = require("js/plugin/loading"); var dialog = require("js/me/dialog"); var $page = $('.records'); var $loadMore = $('.load-more'), $more = $loadMore.children('.more'), $noMore = $loadMore.children('.no-more'); var page = 0; var end = false, loading = false; var winH = $(window).height(); load.init(); function moreRecord(cb) { var count = $page.children('.browse-record-good').length; if (loading) { return; } if (page === 1) { $loadMore.removeClass('hide'); } loading = true; $.ajax({ type: 'GET', url: '/home/recordContent', data: { page: page + 1 }, success: function(data) { if (data === ' ') { end = true; $more.addClass('hide'); $noMore.removeClass('hide'); } else { if (count === 0) { $page.html(data); lazyLoad(); } else { $page.append(data); lazyLoad($page.find('.browse-record-good:gt(' + (count - 1) + ') .lazy')); } window.rePosFooter(); page++; if (cb) { cb(); } } }, complete: function() { loading = false; } }); } load.showLoadingMask(); moreRecord(load.hideLoadingMask); $(window).scroll(function() { if (end) { return; } if (winH + $(window).scrollTop() > $(document).height() - 0.25 * $page.height()) { moreRecord(); } }); $page.on('touchstart', '.del-icon', function() { var $good = $(this).closest('.browse-record-good'), skn = $good.data('skn'); dialog.showDialog({ dialogText: '确定删除此条浏览记录吗?', hasFooter: { leftBtnText: '取消', rightBtnText: '确定' } }, function() { $.ajax({ type: 'GET', url: '/home/delRecord', data: { skn: skn }, success: function(data) { if (data.code === 200) { dialog.showDialog({ dialogText: '删除浏览记录成功', autoHide: 2000, fast: true }); setTimeout(function() { window.history.go(0); }, 1200); } } }); }); }); }); define("js/me/address-act", ["jquery","hammer"], function(require, exports, module){ /** * 修改地址 * @author: bikai<kai.bi@yoho.cn> * @date: 2015/11/30 */ var $ = require("jquery"), Hammer = require("hammer"), tip = require("js/plugin/tip"), security = require("js/plugin/security"), loading = require("js/plugin/loading"); var $addressForm = $('.edit-address'), $submit = $('.submit'), $editAddressPage = $('.my-edit-address-page'), $addressListPage = $('.my-address-list-page'), $backBtn = $('.nav-back'), $navTitle = $('.nav-title'), $input = $('input, textarea'), navTitle = $navTitle.html(), $area = $('.area'), isSubmiting, currentPage = 'edit', newArea = []; $($editAddressPage, $addressListPage).css('min-height', function() { return $(window).height() - $('#yoho-header').height(); }); // 清除返回按钮原有链接 $backBtn.attr('href', 'javascript:void(0);'); // 自定义返回按钮事件 $backBtn.on('touchend', function(e) { if (currentPage === 'list') { $addressListPage.hide(); $editAddressPage.show(); e.preventDefault(); currentPage = 'edit'; $navTitle.html(navTitle); // 恢复默认的三级选择 $addressListPage.hide(); $addressListPage.find('ul').hide().find('li').removeClass('highlight'); $addressListPage.children('ul').show().children('li').show(); newArea = []; } else { window.history.go(-1); } }); // 提交表单请求 $addressForm.on('submit', function() { if (isSubmiting) { return false; } if (security.hasDangerInput(false)) { return false; } // 简单的表单校验 if (!$(this).find('[name="consignee"]').val()) { tip.show('收件人不能为空'); return false; } if (!$(this).find('[name="mobile"]').val()) { tip.show('手机号不能为空'); return false; } if (!$(this).find('[name="area_code"]').val() || !$(this).find('[name="area"]').val()) { tip.show('省市区不能为空'); return false; } if (!$(this).find('[name="address"]').val()) { tip.show('地址不能为空'); return false; } isSubmiting = true; loading.showLoadingMask(); $.ajax({ method: 'POST', url: '/home/saveAddress', data: $(this).serialize() }).then(function(res) { if ($.type(res) !== 'object') { res = {}; } if (res.code !== 200) { tip.show(res.message || '网络出了点问题~'); isSubmiting = false; loading.hideLoadingMask(); } else { window.location.href = '/home/address'; } }).fail(function() { tip.show('网络出了点问题~'); isSubmiting = false; }); return false; }); $submit.on('touchend', function() { if (security.hasDangerInput(false)) { return false; } $input.blur(); $addressForm.submit(); return false; }).on('touchstart', function() { $(this).addClass('highlight'); }).on('touchend touchcancel', function() { $(this).removeClass('highlight'); }); // 省市区列表异步加载 $.get('/home/locationList').then(function(html) { $addressListPage.html(html); // 省市区 $area.on('touchend', function() { $editAddressPage.hide(); $addressListPage.show(); currentPage = 'list'; $navTitle.html('地区选择'); }); // touchend 在下滑的时候会触发 // 省市区联动 $addressListPage.find('.address').each(function(i, elem) { var addressHammer = new Hammer(elem); addressHammer.on('tap', function(e) { var $this = $(e.target); if (e.target.tagName.toLowerCase() !== 'li') { $this = $this.parent('li'); } newArea.push($this.children('.caption').text()); $this.siblings().hide(); $this.children('ul').show().children('li').show(); e.srcEvent.preventDefault(); e.srcEvent.stopPropagation(); }); }); $addressListPage.find('.address-last').each(function(i, elem) { var addressLastHammer = new Hammer(elem); addressLastHammer.on('tap', function(e) { var $this = $(e.target); // 填结果到 html newArea.push($this.children('.caption').text()); $('[name="area"]').val(newArea.join(' ')); $('[name="area_code"]').val($this.data('id')); $editAddressPage.show(); currentPage = 'edit'; $navTitle.html(navTitle); // 恢复默认的三级选择 $addressListPage.hide(); $addressListPage.find('ul').hide().find('li').removeClass('highlight'); $addressListPage.children('ul').show().children('li').show(); newArea = []; e.srcEvent.preventDefault(); e.srcEvent.stopPropagation(); }); }); $addressListPage.on('touchstart', 'li', function() { $(this).addClass('highlight'); }).on('touchend touchcancel', 'li', function() { $(this).removeClass('highlight'); }); }).fail(function() { tip.show('获取省市区列表失败'); }); }); define("js/me/logistic", ["jquery"], function(require, exports, module){ /** * 物流信息页面 * @author: 赵彪<bill.zhao@yoho.cn> * @date: 2015/12/02 */ var $ = require("jquery"), $footer = $('#yoho-footer'); var winH = window.outerHeight, bodyH = document.body.offsetHeight, footH = $footer.height(); function addFooterTopBorder() { if (footH + bodyH > winH) { window.rePosFooter(); } else { $footer.css('border-top', '1px solid #f1f1f1'); } } $(document).ready(addFooterTopBorder); }); define("js/me/pay", ["jquery","hammer"], function(require, exports, module){ /** * 支付页面 * @author: 赵彪<bill.zhao@yoho.cn> * @date: 2015/12/03 */ var $ = require("jquery"); var loading = require("js/plugin/loading"), tip = require("js/plugin/tip"), Hammer = require("hammer"); var theOrderCode = document.getElementById('ordercode').value; var wxPayEl = document.getElementById('weixin'), wxHammer = wxPayEl && new Hammer(wxPayEl); var appIconPosition = { baidu: '-2.7rem', weixin: '-1.2rem', QQ: '-5.4rem', bank: '-4rem' }; //隐藏微信分享选项 if (window.wx) { wx.hideOptionMenu(); } function onBridgeReady() { document.addEventListener('WeixinJSBridgeReady', function() { window.WeixinJSBridge && window.WeixinJSBridge.call('hideOptionMenu'); }); } if (typeof WeixinJSBridge === undefined) { if (document.addEventListener) { document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false); } else if (document.attachEvent) { document.attachEvent('WeixinJSBridgeReady', onBridgeReady); document.attachEvent('onWeixinJSBridgeReady', onBridgeReady); } onBridgeReady(); } else { onBridgeReady(); } //调用微信JS api 支付 function jsApiCall(orderCode, jsApiParameters) { //防止重复操作弹框 window.WeixinJSBridge && window.WeixinJSBridge.invoke( 'getBrandWCPayRequest', jsApiParameters, function(res) { window.location.href = '/home/orders/detail?order_code=' + orderCode; } ); } //微信支付 function callpay(orderCode) { var jsApiParameters; if (typeof WeixinJSBridge === undefined) { if (document.addEventListener) { document.addEventListener('WeixinJSBridgeReady', jsApiCall, false); } else if (document.attachEvent) { document.attachEvent('WeixinJSBridgeReady', jsApiCall); document.attachEvent('onWeixinJSBridgeReady', jsApiCall); } } else { $.ajax({ type: 'GET', url: '/shopping/pay/wechatwapapi?order_code=' + orderCode, dataType: 'json', success: function(res) { if (res.code === 200) { jsApiParameters = res.data.jsApiParameters; jsApiCall(orderCode, jsApiParameters); } else { tip.show('微信支付调取失败'); } }, error: function() { tip.show('请刷新本页面,完成微信支付'); } }); } } function isWXOpen() { var ua = window.navigator.userAgent.toLowerCase(); if (ua.indexOf('micromessenger') > 0) { return true; } else { return false; } } function hideWeChatPay() { var $payApps = $('.app'); $payApps.each(function(idx, app) { if ($(app).parent().attr('id') === 'weixin') { $(app).parent().css('display', 'none'); return false; } }); } function handleForWX() { if (!isWXOpen()) { hideWeChatPay(); } } function setAppIcon(el, position) { $(el).css('background-position-y', position); } function loadIcon() { var $boxs = $('.box'); var $div = null; var appid = null; $boxs.each(function(idx, box) { $div = $(box).find('.icon').find('div'); if ($div.length > 0) { appid = $(box).attr('id'); if (appid !== 'alipay') { setAppIcon($div, appIconPosition[appid]); } } }); } function showPage() { var $pageList = $('.payapp-list'); $pageList.css('visibility', 'visible'); } if (wxHammer) { wxHammer.on('tap', function() { callpay(theOrderCode); }); } function main() { handleForWX(); loading.hideLoadingMask(); showPage(); loadIcon(); } loading.showLoadingMask(); window.onload = main; }); define("js/me/personal-details", ["jquery"], function(require, exports, module){ /** * 个人信息 * @author: bikai<kai.bi@yoho.cn> * @date: 2015/11/19 */ var $ = require("jquery"); var $userAvatar = $('.user-avatar'); var myImage = new Image(), avatar; // 部分老用户没有头像,显示默认头像 avatar = $userAvatar.data('avatar'); myImage.src = avatar; myImage.onload = function() { $userAvatar.css('background-image', 'url(' + avatar + ')'); }; });