mobile.js 16.2 KB
/**
 * @h5页面js
 * @author:liuyue
 * @date:2015-05-20
 **/

define('mobile', function(require, exports) {
    var $ = require('jquery'),
        swipe = require("plugins/swipe"),
        share = require("plugins/share"),
        store = require("lib/util/store"),
        tools = require("lib/util/tools"),
        swiper = require("plugins/idangerous.swiper"),
        mlellipsis = require("plugins/mlellipsis");
    require("plugins/imgZoom");
    exports.common = function() {
        var downloadH,
            scrollTop;
        if ($('.header-download').size() > 0) {
            downloadH = $('.header-download').height();
            //顶部app下载位置
            $(window).on('scroll', function() {
                scrollTop = $(window).scrollTop();
                if (!$('.search-wrap input').hasClass('show')) {
                    if (scrollTop >= downloadH) {
                        $('.header-download').addClass('fix');
                        $('.header-download-wrap').addClass('show');
                    } else {
                        $('.header-download').removeClass('fix');
                        $('.header-download-wrap').removeClass('show');
                    }
                }
            });
            if (tools.cookie('download_state')) {
                $('.header-download-wrap').remove();
            } else {
                $('.header-download-wrap').show();
            }
            //关闭下载
            $('.header-download-wrap').on('click', '.tip-close', function() {
                $('.header-download-wrap').remove();
                tools.cookie('download_state', 1);
            });
        }
        
        //上拉刷新
    	window.loadheight = $('#hook').height();
        window.hidden = $("#hook").animate("marginTop", "-" + loadheight + "px");
        window.visible = $("#hook").animate("marginTop", "0px");
        $("#hook").css("marginTop", "-" + loadheight + "px");
        var loadheight = $('#hook').height();
        $(window).scroll(function (event) {
            var st = $(window).scrollTop();
            if (st <= 0) {
                $("#hook").animate({
                    "marginTop": "0px"
                }, 200);
                //隐藏层出现,不刷新
            	if($(".overlay").css("display") == "block") {
            		return true;
            	};
            	//是不是允许刷新
            	if($("#hook").attr("disloading") == "1"){
            		$("#hook").attr("disloading", "0");
            		return true;
            	}
                $("#hook").delay(500).slideUp(200, function () {
                    window.location.reload()
                })
            }
            if ($.browser.webkit) {
                if (st == 0) {
                    $('body').css('overflow', 'hidden')
                }
            }
        });
        
        //屏幕静止滚动
        $("body").bind('touchmove', function(event)
        {
        	//隐藏层出现,屏幕静止滚动
	       	if($(".overlay").css("display") == "block") {
	       		event.preventDefault();
	       	}
	       	return true;
        });
    };

    exports.index = function() {
        var bannerSwiper;
        if ($('.slide-box').find('.box').size() > 1) {
            bannerSwiper = new swiper('.slide-box', {
                wrapperClass: 'slide-wrap',
                slideClass: 'box',
                autoplay: 5000,
                loop: true,
                pagination: '.slide-navigator .dib',
                paginationElement: 'a',
                autoplayDisableOnInteraction: false
            });
        }
        if ($('.slide-navigator .dib').find('a').size() <= 1) {
            $('.slide-navigator').hide();
        }
        //频道点击效果
        /*$('.channel-list').on('tap', 'li', function() {
            $(this).addClass('current').siblings().removeClass('current');
        });*/
    };
    exports.activity = function() {
        $('.content-tab').on('click', 'li', function() {
            var nowIndex = $(this).index();
            $(this).addClass('current').siblings().removeClass('current');
            $('.content-main').hide().eq(nowIndex).show();
        });

    };
    exports.brand = function(event) {
        var bannerSwiper;
        var getBrand = function() {
            var brand = $.trim($("input[type='text']").val());
            var client = $(".search-btn").attr("client");
            console.log(client);
            var template = '<ul class="brand-list cooperation-list clearfix">{li}</ul>';
            var noSearchTemplate = '<div class="no-search" style="display:block;"><p>未搜索到“{brand}”的相关品牌</p><a href="javascript:;" class="all_brand"><查看全部品牌</a></div>';
            var html = '';
            $.ajax({
                type: "post",
                url: "/brand/getbrand",
                data: {
                    brand: encodeURIComponent(brand)
                },
                dataType: 'json',
                success: function(data) {
                    var brands = data.data;
                    if (data.code == 200 && brands != "") {
                        $.each(brands, function(k, v) {
                            html += '<li><a href="/brand/detail/id/' + v.id + '/client/'+client+'" title="' + v.name + '"><div class="img-box">' +
                                '<img src="' + tools.getImages(v.logo, '0145x0097', 'blogimg', 'primary') + '" alt="" alt="' + v.name + '"></div>' +
                                '<p>' + v.name + '</p></a></li>';
                        });
                        $(".brand-content").html(template.replace('{li}', html));
                    } else {
                        $(".brand-content").html(noSearchTemplate.replace('{brand}', tools.escapeHTML(brand).replace(/\"/g,"“").replace(/\'/g,"‘")));
                    }
                    //禁止刷新
                    $("#hook").attr("disloading", "1");
                }
            });
        };

        //大banner滑动
        if ($('.slide-box').find('.box').size() > 1) {
            bannerSwiper = new swiper('.slide-box', {
                wrapperClass: 'slide-wrap',
                slideClass: 'box',
                loop: true,
                pagination: '.slide-navigator .dib',
                paginationElement: 'a',
                autoplay: 5000,
                autoplayDisableOnInteraction: false
            });
        }
        //banner只有一张图时不显示小圆点
        if ($('.slide-navigator .dib').find('a').size() <= 1) {
            $('.slide-navigator').hide();
        }

        //搜索框获得焦点
        $('.search-wrap input').on('focus', function() {
            var offsetTop = $('.search-wrap').offset().top;
            $('.overlay').addClass('show');
            $(this).removeClass('show').addClass('show');

            $('body,html').animate({
                scrollTop: offsetTop
            });
        });
        $('.search-wrap').find('input').on('keyup', function(event) {
            var keycode = event.which;
            if (keycode == 13) {
                $('.search-wrap input').blur();
            }
        });
        $('.search-btn').on('tap', function() {
            $('.search-wrap input').focus().addClass('hasVal');
        });
        //获取所有品牌
        $(".all_brand").live("click", function() {
            $("input[type='text']").val("");
            getBrand();
        });
        $('.search-wrap input').on('blur', function() {
            var txtInput = $(this);
            $('.overlay').removeClass('show');
            if (txtInput.val() === '') {
                txtInput.removeClass('hasVal');
            } else {
                txtInput.addClass('hasVal');
            };
            getBrand();
            //禁止刷新
            $("#hook").attr("disloading", "1");
        });
        //搜索存在,调用
        if($(".search-wrap").size()){
        	getBrand();
        }
    };
    exports.scene = function() {
        $('.scene-tab').on('tap', 'li', function() {
            var nowIndex = $(this).index();
            if ($(this).hasClass('disable')) return;
            $(this).addClass('current').siblings().removeClass('current');
            $('.main-layout').removeClass('current').eq(nowIndex).addClass('current');
        });
        $('.scene-content').find('.layout-item').each(function() {
            $(this).imgZoom();
        });
    };

    exports.detail = function() {
        var shareUrl = $(".share").attr("data-link"),
            shareCover = $(".share").attr("cover-url"),
            detailTitle = $('.detail-title').find('.title'),
            detailSubtitle = $('.detail-title').find('.subtitle'),
            slideSwiper;
        mlellipsis.init();

        //多图滑动
        if ($('.slide-box').find('.box').size() > 1) {
            slideSwiper = new swiper('.slide-box', {
                wrapperClass: 'slide-wrap',
                slideClass: 'box',
                loop: true,
                pagination: '.slide-navigator .dib',
                paginationElement: 'a',
                autoplay: 5000,
                autoplayDisableOnInteraction: false
            });
        }
        if ($('.slide-navigator .dib').find('a').size() <= 1) {
            $('.slide-navigator').hide();
        }
        //截字
        $('.related-post').find('.content').each(function() {
            $(this)[0].mlellipsis(2);
        });
        //分享
        share.init({
            shareUrl: shareUrl,
            img: shareCover,
            sinaText: '【YOHOOD 2015】' + detailTitle.text() + '@YOHO潮流志',
            fbTextFunction: function() {
                return {
                    des: '【YOHOOD 2015】' + detailTitle.text(),
                    name: '【YOHOOD 2015】' + detailTitle.text(),
                    caption: '【YOHOOD 2015】' + detailTitle.text(),
                    url: location.href
                }
            },
            tweetText: '【YOHOOD 2015】' + detailTitle.text(),
            qqText: '【YOHOOD 2015】' + detailTitle.text() + '#YOHOOD 2015'
        });
        var videoSize = $("video").size();
        var videoPos = 0;
        if (videoSize > 0) {
            var videoInterval = setInterval(
                function() {
                    $("video").each(function() { //设置视频高度
                        if ($(this)[0].videoHeight > 0) {
                            $(this).css({
                                "height": Math.floor($(this)[0].videoHeight * (300 / $(this)[0].videoWidth))
                            });
                            videoPos++;
                        }
                    });
                    if (videoPos >= videoSize) clearInterval(videoInterval);
                }, 20);
        }
    };

    exports.show = function() {
        $(".layout-item").bind("click", function(event) {
            if ($(this).attr("isopen") == 1) {
                $(this).find(".image-box .pic-tip").each(function() {
                    $(this).css({
                        display: "none"
                    });
                });
                $(this).attr("isopen", 0);
            } else {
                var imageWidth = $(window).width(),
                    imageHeight = 320;
                $(this).find(".image-box .pic-tip").each(function() {
                    var style_left = parseInt($(this).attr("x")) / 10000 * imageHeight;
                    var style_top = parseInt($(this).attr("y")) / 10000 * imageWidth;
                    $(this).css({
                        top: style_top,
                        left: style_left,
                        display: "block"
                    });

                });
                $(this).attr("isopen", 1);
            }
        });
    };

    exports.news = function() {
        $('select').on('change', function() {
            window.location.href = $(this).val();
        });
        var current_tag = $(".main-layout").attr("current_tag");
        var client = $(".main-layout").attr("client");
        var url = current_tag == "" ? "/news/index" : "/news/index/tag/" + current_tag;
        var prevPage = '<a href="{url}"><span class="iconfont">&#xe60f;</span>&nbsp;PREV</a>';
        var lastPage = '<a href="{url}" class="next">NEXT&nbsp;<span class="iconfont">&#xe610;</span></a>';
        var pageHtml = '<div id="pageContent" style="text-align: center;" class="pagination">' +
            '<div class="pagination-inner clearfix" id="img_page" model="default" rel="">{prevPage}{lastPage}</div></div>';
        var getPagination = function(page, totalPage) {
            if ($("#pageContent").size() > 0) {
                return ""
            }
            if (page - 1 >= 1) {
                prevPage = prevPage.replace("{url}", url + "/page/" + ((page - 1) * 4 - 3) + "/client/" + client);
                pageHtml = pageHtml.replace("{prevPage}", prevPage);
            }
            if (page < totalPage) {
                lastPage = lastPage.replace("{url}", url + "/page/" + (page * 4 + 1) + "/client/" + client);
                pageHtml = pageHtml.replace("{lastPage}", lastPage);
            }
            if (page < 1) {
                pageHtml = '';
            }
            pageHtml = pageHtml.replace("{prevPage}", "").replace("{lastPage}", "");
            return pageHtml;
        }
        $(window).bind("scroll", function() {
            var total = $(".main-layout").attr("total");
            var ajaxPage = $(".main-layout").attr("page"); //ajax请求的page
            var total_times = parseInt($(".main-layout").attr("total_times"));
            var limit = parseInt($(".main-layout").attr("limit"));
            var times = $(".main-layout").attr("times") ? $(".main-layout").attr("times") : 0;
            var page = Math.ceil(parseInt(ajaxPage) / (total_times + 1));
            var totalPage = Math.ceil(total / (limit * (total_times + 1)));
            if ($(window).scrollTop() >= $(document).height() - $(window).height() - 50) {
                if (total > limit && times < total_times && page <= totalPage) {
                	if($(".main-layout").attr("is_ajax") == 1 || $("#img_page").size())
                    {
                		return true;
                    }
                	$(".main-layout").attr("is_ajax", 1);
                    $.ajax({
                    	beforeSend:function() {
                    		if($(".loading").size() == 0) {
                    			$(".main-layout").append('<div class="loading" style="left: 47.5%;position:absolute;"><img src="'+ YohoConfig.resUrl + 'images/yohood/loading.gif'+'" /></div>');
                    	    }
                    		return true;
                    	},
                        type: "get",
                        url: url + "/page/" + (parseInt(ajaxPage) + 1),
                        success: function(data) {
                            var news_page = $(data);
                            page = Math.ceil(parseInt(news_page.attr("page")) / (total_times + 1)); //实现页码
                            if ($(".main-layout").attr("page") != news_page.attr("page") && news_page.html() != "") {
                                $(".main-layout").append(news_page.html());
                                $(".main-layout").attr({
                                    "total": news_page.attr("total"),
                                    "page": news_page.attr("page"),
                                    "times": ++times
                                });
                                //console.log(news_page.attr("page"));
                                //console.log("times:" + times);
                                //console.log("page:" + page);
                                //console.log("totalPage:" + totalPage);
                            }     
                        	if($(".loading").size()){
                        		$(".loading").remove();
                        	}
                            if (times == total_times || news_page.html() == "" || page == totalPage) {
                                $(".main-layout").append(getPagination(page, totalPage));
                            }
                            $(".main-layout").attr("is_ajax", 0);
                        }
                    });
                } else if (page == totalPage) {
                    $(".main-layout").append(getPagination(page, totalPage));
                }
                return false;
            }
        });
    };
});