js ajax请求拦截,请求加载动画,多页面hash虚拟路由(由iframe实现)

就像标题说的,有这么些功能。因为业务原因,里面还嵌入了点不得不加的冗余判断,使用的时候,参考着看看,删除掉多余的代码

(() => {
    let loadingDom = $(`
                <div class='ajax-loading'style="display: flex;align-items: center;justify-content: center;flex-direction: column;position:fixed;left:0;right:0;bottom:0;top:0;z-index:9999999999999;display:none">
                    <div style="display: flex;align-items: center;justify-content: center;flex-direction: column;width:120px;height:120px;border-radius: 17px;box-shadow: 0px 2px 16px 1px rgba(229,229,229,0.3);background: white;">
                       <svg version="1.1" id="loader-1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="60px" height="60px" viewBox="0 0 40 40" enable-background="new 0 0 40 40" xml:space="preserve">
                          <path opacity="0.2" fill="#FF6700" d="M20.201,5.169c-8.254,0-14.946,6.692-14.946,14.946c0,8.255,6.692,14.946,14.946,14.946
                            s14.946-6.691,14.946-14.946C35.146,11.861,28.455,5.169,20.201,5.169z M20.201,31.749c-6.425,0-11.634-5.208-11.634-11.634
                            c0-6.425,5.209-11.634,11.634-11.634c6.425,0,11.633,5.209,11.633,11.634C31.834,26.541,26.626,31.749,20.201,31.749z">
                          </path>
                          <path fill="#FF6700" d="M26.013,10.047l1.654-2.866c-2.198-1.272-4.743-2.012-7.466-2.012h0v3.312h0
                            C22.32,8.481,24.301,9.057,26.013,10.047z">
                            <animateTransform attributeType="xml" attributeName="transform" type="rotate" from="0 20 20" to="360 20 20" dur="0.5s" repeatCount="indefinite"></animateTransform>
                          </path>
                        </svg>
                        <div style="color:#FF4F00;font-size:14px;line-height:20px;margin-top:12px;">加载中</div>
                    </div>
                </div>
            `)
    let toastDom = $(`
                <div class='ajax-toast-contanier' style="display:none; box-sizing: border-box;margin: 0;padding: 0;color: rgba(0, 0, 0, .55);font-size: 13px;line-height: 1;list-style: none;z-index: 1010;width: 100%;pointer-events: none;text-align: center;padding:8px">
                    最底部了~
                </div>
            `)

    function toastAjax(str) {

    }
    $(() => {
        loadingDom.appendTo('body');

        toastDom.appendTo('body');
    })

    let origin = XMLHttpRequest.prototype.open;
    XMLHttpRequest.prototype.open = function (...args) {
        // 设置send jq的 ajax 失效了,所以注销
        //let post_data = []  
        //let send = this.send;
        //this.send = function (...data) {
        //    post_data = data;
        //    return send.apply(_this, data)
        //}
        (() => { //可以在这里插入open拦截代码,和生命周期其他的东西
            loadingDom.show().css('display', 'flex');
            document.documentElement.style.overflow = 'hidden' // loading的显示初始化


            toastDom.css('display', 'none');
        })()
        this.__on_response = function (res) { //reponse拦截,如果jq后加载拦截不住jq 的 ajax请求
            return res
        }
        this.addEventListener('readystatechange', function (res) {
            if (this.readyState === 4) {
                if (this.status == 200) {

                } else {

                }
                loadingDom.fadeOut();
                if (this.responseURL.indexOf('GetCategoryTypeHandler.aspx') > -1) {

                } else {
                    document.documentElement.style.overflow = ''
                }
            }
        }, false)
        return origin.apply(this, args);
    };
    var accessor = Object.getOwnPropertyDescriptor(
        XMLHttpRequest.prototype,
        "response"
    );

    Object.defineProperty(XMLHttpRequest.prototype, "response", {
        get: function () {
            let response = accessor.get.call(this);
            //在__on_response里修改你的response
            response = this.__on_response(response)
            return response;
        },
        set: function (str) {
            return accessor.set.call(this, str);
        },
        configurable: true,
    });
    let notNextUrl = '';
    $.ajaxSetup({
        //dataFilter(datatype) 用于处理XMLHttpRequest 原始响应数据的函数(注意是返回数据)
        dataFilter(data, type) {
            if (data != null && data.length > 0) {
                let dataJson = JSON.parse(data);
                if (dataJson.code == 200) {
                    if (notNextUrl) {
                        notNextUrl = '';
                    }
                }
                else if (dataJson.code == 204) {
                    if (this.url.indexOf('page=1') > -1) { // 第一页就没有数据就不加翻页到底的提示了,直接alert提示数据为空
                        //alert(dataJson.msg)
                    } else { // 非第一页就没有数据加 翻页到底的提示
                        toastDom.css('display', 'block');
                        notNextUrl = this.url;
                    }

                }
                else if (dataJson.code == 302) {
                    if (this.url.indexOf('/handler/OrderHandler.aspx?type=getPromoteGoodsLink') > -1) {
                        return data
                    }
                    if (confirm('您的登录已过期,请重新登录')) {
                        let win = GetWindow();
                        win.location.href = ("/wxlogin.aspx?returnurl=" + encodeURI(win.location.href));
                    }
                }
                else if (dataJson.code == 209) {
                    if (!window.layer) {
                        alert(dataJson.msg);
                        window.history.go(-1)
                    } else {
                        layer.alert(dataJson.msg, { "btn": "知道了", title: '提示' }, function () {
                            window.history.go(-1);
                        });
                    }
                }
                else {
                    if (this.url.indexOf('/handler/GetMallColumn.aspx') > -1) {
                        return
                    }
                    alert(dataJson.msg)
                }
            }
            return data
        },
        beforeSend(xhr) {
            if (this.url == notNextUrl) {
                return false
            }
        }
    })
   
})();


(function () {
    if (typeof WeixinJSBridge == 'object' && typeof window.WeixinJSBridge.invoke == 'function') {
        handleFontSize();
    } else {
        if (document.addEventListener) {
            document.addEventListener('WeixinJSBridgeReady', handleFontSize, false);
        } else if (document.attachEvent) {
            document.attachEvent('WeixinJSBridgeReady', handleFontSize);
            document.attachEvent('onWeixinJSBridgeReady', handleFontSize);
        }
    }

    function handleFontSize() {
        // 设置网页字体为默认大小
        window.WeixinJSBridge.invoke('setFontSizeCallback', { 'fontSize': 0 });
        // 重写设置网页字体大小的事件
        window.WeixinJSBridge.on('menu:setfont', function () {
            window.WeixinJSBridge.invoke('setFontSizeCallback', { 'fontSize': 0 });
        });
    }
})();


(function () { // 用来解决多页面应用,不能保持跳转页面后回到原页面不能保持状态的问题。 自定义hash路由。
    let ua = navigator.userAgent.toLowerCase();
    let isMini = ua.indexOf('miniprogram') !== -1;
    if (isMini && !window.wx) { //如果是小程序环境,引入两端交互的js
        document.write('<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"><\/script>');
    }//iframe里调用wx会出问题所以,给所有页面加个wx的jssdk

    let iframeDom;

    window.addEventListener('hashchange', function (e) {
        routerHandle(e);
    }, false);
    window.addEventListener("beforeunload", (event) => { //页面离开监听

    });
    window.addEventListener("load", (event) => { // 页面进入监听
        
        if (window.performance && window.performance.navigation) {
            restoreIframeState()
            if (window.performance.navigation.type === 0) {
                console.log('页面是通过链接、地址栏或 JavaScript API 进入的');
                const navigationEntries = window.performance.getEntriesByType('navigation');
                if (navigationEntries.length > 0 && navigationEntries[0].type === 'reload') {//页面是通过刷新进入的
                    
                } else {
                    
                }
            } else if (window.performance.navigation.type === 1) {
                console.log('页面是通过刷新进入的');
            } else if (window.performance.navigation.type === 2) {
                console.log('页面是通过前进或者后退按钮进入的');
            } else if (window.performance.navigation.type === 255) {
                console.log('通过浏览器扩展或者其他非标准的方式加载页面');
            }
        }  
    });
    function routerHandle(e) {
        let newURL = e.newURL;
        let oldURL = e.oldURL;
        iframeControler(newURL);
    }
    //下面为页面监听用到的公用方法
    function restoreIframeState() { // 用来恢复 页面详情页的iframe状态
        iframeControler(window.location.href)
    }
    function iframeControler(href) { // iframe控制器
        let hashStr = href.substring(href.indexOf('#'));
        if (hashStr.indexOf('#gooddetails') > -1) {
            let query = hashStr.substring(hashStr.indexOf('?'));
            query = addparams(query, `time=${new Date().getTime()}`);
            iframeDom = $(`<iframe src="/goods/gooddetails.aspx${query}" style="position:fixed; left:0; right:0; top:0; bottom:0; z-index:1000; width: 100%; height: 100%; border: none;background: white;"></iframe>`);
            $('body').append(iframeDom);
            document.documentElement.style.overflow = 'hidden'
        } else {
            if (iframeDom) {
                iframeDom.remove();
                iframeDom = null;
                document.documentElement.style.overflow = ''
            }
        }
    }
    function addparams(url, param) {
        let urlParameter = url.substr(url.indexOf('?'));
        let urlhost = url.substr(0, url.indexOf('?')) + '?';
        let query = urlParameter.substring(1);
        let vars = query.split("&");
        let params = param.split("&");
        let allParamsArr = vars.concat(params);
        let resultArr = [];
        allParamsArr.forEach(item => {
            let find = resultArr.findIndex(i => {
                return i.indexOf(item.split('=')[0]) > -1
            })
            if (find === -1) {
                resultArr.push(item)
            } else {
                resultArr[find] = item
            }
        })
        let resultUrl = urlhost + allParamsArr.join('&');
        return resultUrl
    }
})();

// 下面为公共方法
function GetWindow(def) { //用来在iframe中获取最外层的window
    let win = def || window;
    if (win === win.parent) {
        return win
    } else {
        return arguments.callee(win.parent)
    }
}
function GetQueryVariable(variable) { //获取url参数
    var urlParameter = window.location.search;
    var query = urlParameter.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
        var index = vars[i].indexOf('=');
        if (vars[i].substr(0, index) == variable) {
            return decodeURIComponent(vars[i].substr(index + 1))
        }
    }
    return '';
}

下面为预览页

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="hotsales.aspx.cs" Inherits="Thsb.WWW.goods.hotsales" %>

<!DOCTYPE html>
<%@ Register Src="/modules/textCopyPopup.ascx" TagPrefix="textCopyPopup" TagName="textCopyPopup" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>爆款推荐</title>
    <meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1, initial-scale=1, user-scalable=no, viewport-fit=cover" />
    <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests" />
    <link rel="stylesheet" href="<%=Thsb.Config.ConfigInfo.OssStatic.Domain %>/css/default_mobile.css?v=<%=Thsb.Config.ConfigInfo.OssStatic.Version %>" />
    <link rel="stylesheet" href="<%=Thsb.Config.ConfigInfo.OssStatic.Domain %>/css/reward-research.css?v=<%=Thsb.Config.ConfigInfo.OssStatic.Version %>" />
    <link rel="stylesheet" href="<%=Thsb.Config.ConfigInfo.OssStatic.Domain %>/css/hotsales.css?v=<%=Thsb.Config.ConfigInfo.OssStatic.Version %>">
    <link rel="stylesheet" href="<%=Thsb.Config.ConfigInfo.OssStatic.Domain %>/css/swiper.min.css?v=<%=Thsb.Config.ConfigInfo.OssStatic.Version %>">

    <script src="//cdn.staticfile.org/jquery/3.6.1/jquery.min.js"></script>
    <script src="<%=Thsb.Config.ConfigInfo.OssStatic.Domain %>/js/XMLHttpRequestIntercept.js?v=<%=Thsb.Config.ConfigInfo.OssStatic.Version %>" type="text/javascript"></script>
    <script src="<%=Thsb.Config.ConfigInfo.OssStatic.Domain %>/js/swiper.min.js?v=1" type="text/javascript"></script>
    <script type="text/javascript">
        !window.jQuery &&
            document.write(
                `<script src="<%=Thsb.Config.ConfigInfo.OssStatic.Domain %>/js/jquery-3.6.1.min.js"><\/script>
                <script src="<%=Thsb.Config.ConfigInfo.OssStatic.Domain %>/js/XMLHttpRequestIntercept.js?v=<%=Thsb.Config.ConfigInfo.OssStatic.Version %>" type="text/javascript"><\/script>
                <script src="<%=Thsb.Config.ConfigInfo.OssStatic.Domain %>/js/swiper.min.js?v=1" type="text/javascript"><\/script>`
            );
    </script>
    <link rel="stylesheet" href="<%=Thsb.Config.ConfigInfo.OssStatic.Domain %>/css/layer.css?v=1" />
    <script src="<%=Thsb.Config.ConfigInfo.OssStatic.Domain %>/js/layer.js?v=1" type="text/javascript"></script>
    <link rel="stylesheet" href="<%=Thsb.Config.ConfigInfo.OssStatic.Domain %>/css/iframeLayer.css?v=<%=Thsb.Config.ConfigInfo.OssStatic.Version %>">
    <script src="<%=Thsb.Config.ConfigInfo.OssStatic.Domain %>/js/moment.min.js?v=<%=Thsb.Config.ConfigInfo.OssStatic.Version %>" type="text/javascript"></script>
    <script> moment.locale("zh-cn"); </script>
    <style>
        body {
            overflow-x: hidden;
            background: url('<%=Thsb.Config.ConfigInfo.OssStatic.Domain %>/image/hotsales/bac.png') 0% 0%,#401A03;
            background-repeat: no-repeat;
            background-size: 100%;
        }

        .hot-sales-card {
            padding-top: 42.73%;
            position: relative;
            background: url('<%=Thsb.Config.ConfigInfo.OssStatic.Domain %>/image/hotsales/card.png') 0% 0%;
            background-repeat: no-repeat;
            background-size: 100%;
            margin-bottom: 10px;
        }

        .JDLMcontent_item_right_middle .rebate-card {
            height: 17px;
            line-height: 17px;
            min-width: 28px;
            margin-right: 4px;
            background: url('<%=Thsb.Config.ConfigInfo.OssStatic.Domain %>/image/productlist/rebate-card-left.png') 0% 0% / 20px 100% no-repeat, url('<%=Thsb.Config.ConfigInfo.OssStatic.Domain %>/image/productlist/rebate-card-right.png') 100% 0% / 4px 100% no-repeat, linear-gradient(to right,transparent 0, transparent 20px,#FFDE15 20px, #FFDE15 calc(100% - 4px), transparent calc(100% - 4px), transparent 100%);
            padding-left: 24px;
            padding-right: 4px;
            text-align: right;
            color: #333138;
            margin-top: 4px;
        }

        .JDLMcontent_item_right_middle .certificate-card {
            height: 17px;
            line-height: 17px;
            min-width: 28px;
            margin-right: 4px;
            background: url('<%=Thsb.Config.ConfigInfo.OssStatic.Domain %>/image/productlist/certificate-card-left.png') 0% 0% / 20px 100% no-repeat, url('<%=Thsb.Config.ConfigInfo.OssStatic.Domain %>/image/productlist/certificate-card-right.png') 100% 0% / 4px 100% no-repeat, linear-gradient(to right,transparent 0, transparent 20px,#FF8B2F 20px, #FF8B2F calc(100% - 4px), transparent calc(100% - 4px), transparent 100%);
            padding-left: 24px;
            padding-right: 4px;
            text-align: right;
            color: white;
            margin-top: 4px;
        }
        
        .ajax-toast-contanier{
            color: white!important;
        }
        body.activity  .ajax-toast-contanier{
            color: rgba(0, 0, 0, 0.55)!important;
            background: #F9F9F9
        }

        .to-index{
            position: fixed;
            left: 0;
            top: 17px;
            padding: 6px 13px;
            background: #0000004D;
            border-radius: 0px 54px 54px 0px;
            z-index: 5;
            color: white;
            font-size: 24px;
        }
    </style>
</head>
<body>
    <a href="/" class="iconfont to-index">&#xe65c;</a>
    <div class="activity-card">
        <img src="<%=Thsb.Config.ConfigInfo.OssStatic.Domain %>/image/hotsales/red-envelope-bac.png"/>
        <div class="activity-card-content">
            <div class="activity-card-tips">
                <div class="activity-card-tag">京东购物红包</div>
                <div class="activity-card-tips-btn">补贴规则</div>
            </div>
            <div class="activity-card-balance">
                <span>可用补贴</span>
                <span class="activity-card-balance-val">88</span>
                <span></span>
            </div>
            <div class="activity-card-balance-tips">以下仅京东商品可使用补贴进行抵扣</div>
            <div class="activity-card-countdown">
                <div class="count-down-box">
                    <div class="day">--</div>
                    <div></div>
                    <div class="hour">--</div>
                    <div></div>
                    <div class="minute">--</div>
                    <div></div>
                    <div class="second">--</div>
                    <div>秒后失效</div>
                </div>
            </div>
        </div>
    </div>
    <div class="hot-sales">
        <div class="hot-sales-card">
          
        </div>

        <div class="JDLMtabList">
            
        </div>

        <div class="JDLMcontent">
            
        </div>
    </div>
    
</body>
<textCopyPopup:textCopyPopup runat="server" ID="textCopyPopup" />
<script>
    let ua = navigator.userAgent.toLowerCase();
    let isMini = ua.indexOf('miniprogram') !== -1;

    // 点击商品跳转
    function goodsClick(mallType, skuid, couponLink, idSign, OriPrice, CouponAmount, Gift, Price, Name) {
        if (Gift && Gift!='null') {
            let popup = $(` 
                <div class="activity-popup">
                    <div class="activity-popup-mask"></div>
                    <div class="activity-popup-content">
                        <div class="activity-popup-title">${Name}</div>
                        <div class="activity-popup-row">
                            <div>京东价</div>
                            <div>¥<span class="activity-popup-row-val">${OriPrice}</span></div>
                        </div>
                        <div class="activity-popup-row subtraction">
                            <div>优惠券</div>
                            <div>-¥<span class="activity-popup-row-val">${CouponAmount}</span></div>
                        </div>
                        <div class="activity-popup-row subtraction">
                            <div>购物补贴</div>
                            <div>-¥<span class="activity-popup-row-val">${Gift}</span></div>
                        </div>
                        <div class="activity-popup-row">
                            <div>补贴后</div>
                           <div>¥<span class="activity-popup-row-val">${Price}</span></div>
                        </div>
                        <div class="activity-popup-btn">领取优惠券购买</div>
                    </div>
                </div>
            `);
            $('body').append(popup);
            popup.on('click', '.activity-popup-mask', function () {
                popup.remove();
            })
            popup.on('click', '.activity-popup-btn', function () {
                goodsClick(mallType, skuid, couponLink, idSign);
                popup.remove();
            })
        } else {
            let newurl = `gooddetails?time=${new Date().getTime()}&isPopular=1&source=${mallType}&goodid=${skuid}`;
            if (mallType == '2') {
                newurl += "&searchid=" + couponLink;
                newurl += "&idsign=" + idSign;
            } else if (mallType == '3') {
                newurl += "&couponlink=" + couponLink;
            } else if (mallType == '1') {
                newurl += "&couponlink=" + couponLink;
            }
            location.hash = newurl;
        }
    }
    class Init {
        constructor() {
            this.contanier = $('body');
            this.tagContanier = $('.JDLMtabList');
            this.cardContanier = $('.hot-sales-card');
            this.contentContanier = $('.JDLMcontent');
            this.page = 1;
            this.pageTemp = 1;
            this.pageTemp = 1;
            this.maxPage = 50;
            this.pageSize = 10;
            this.tag = null;
            this.PopularGoodList = [];
            this.Tags = [];
            this.Items = [];
            this.index = 0;

            // 活动相关参数
            this.TotalDiscount = 0;
            this.EndTime = '2023-08-03 16:11:00';
            this.inprogress = false;
            this.run().then(() => {
                this.initDom();
                this.bindEvent();
                this.writeDom();
            });
        }
        async run(isPageTurning) {
            if (!isPageTurning) {
                this.page = 1;
                this.pageTemp = 1;
            }
            if (this.page != this.pageTemp) { throw new Error('到最后一页了') }
            return this.getData(isPageTurning).then((result, status, xhr) => {
                if (result.success && result.data) {
                    this.PopularGoodList = result.data.Filter.PopularGoodList;
                    this.Tags = result.data.Filter.Tags;
                    this.Items = result.data.Items;
                    this.TotalDiscount = result.data.Filter.TotalDiscount || 0;
                    this.EndTime = result.data.Filter.EndTime || moment().format('YYYY-MM-DD HH:mm:ss');

                    let time = moment(this.EndTime).diff(moment());
                    if (time <= 0) {
                        this.inprogress = false;
                    } else {
                        this.inprogress = true;
                    }
                }
            }, () => {

            })
        }
        initDom() {
            if (this.inprogress) {
                this.contanier.find('.activity-card-balance-val').html(this.TotalDiscount);
                this.contanier.addClass('activity');

                this.timer && clearInterval(this.timer);
                this.timer = setInterval(() => {
                    let time = moment(this.EndTime).diff(moment())
                    if (time <= 0) {
                        clearInterval(this.timer);
                        this.inprogress = false;
                        this.contanier.removeClass('activity');
                        return
                    }
                    let t = time / 1000;
                    let d = Math.floor(t / (24 * 3600));  //剩余天数,如果需要可以自行补上
                    //let h = Math.floor((t - 24 * 3600 * d) / 3600) + d * 24;  //不需要天数,把天数转换成小时
                    let _h = Math.floor((t - 24 * 3600 * d) / 3600)  //保留天数后得小时
                    let m = Math.floor((t - 24 * 3600 * d - _h * 3600) / 60);
                    let s = Math.floor((t - 24 * 3600 * d - _h * 3600 - m * 60));

                    $('.count-down-box>.day').html(d);
                    $('.count-down-box>.hour').html(_h);
                    $('.count-down-box>.minute').html(m);
                    $('.count-down-box>.second').html(s);
                }, 1000, true)
            }
        }
        bindEvent() {
            let that = this;
            $(window).scroll(function () {
                var nowScrolledHeight = document.documentElement.scrollTop || document.body.scrollTop;
                var docHeight = document.body.clientHeight;
                var pageHeight = window.innerHeight;
                var go = parseInt(docHeight) - parseInt(pageHeight);
                nowScrolledHeight = Math.ceil(nowScrolledHeight);
                if (nowScrolledHeight >= go) {
                    if (that.page <= that.maxPage) {
                        that.run(true).then((e) => {
                            that.writeDom(true);
                        }).catch(err => {
                            console.log(err)
                        });
                    }
                }
            });

            this.contanier.on('click',".JDLMtabList>.JDLMtabList-div", function () {
                $(this).addClass("active").siblings().removeClass("active");
                $(this).siblings().find(".line").removeClass("line");
                $(this).find("span").addClass("line");
                var index = $(".JDLMtabList>.JDLMtabList-div").index(this);
                if (index !== that.index) {
                    that.index = index;
                    var $currentEl = $(".JDLMcontent")[0];
                    
                    let targetScollTop = $currentEl.offsetTop - 46;
                    if (document.documentElement.scrollTop > targetScollTop) {
                        $('html,body').animate({ scrollTop: targetScollTop }, 50);
                    }
                    that.tag = $(this).text().replace(/\s*/g, "");
                    that.run().then(() => {
                        that.writeContent();
                    });
                }
            });


            function dragMoveX(container) {
                var flag;
                var downX;
                var scrollLeft;
                //鼠标按下
                $(document.body).on("mousedown", container, function (event) {
                    console.log('mousedown')
                    flag = true;
                    downX = event.clientX;
                    scrollLeft = $(this).scrollLeft();
                });
                //鼠标移动
                $(document).on("mousemove", function (event) {
                    console.log('mousemove', flag, event.clientX)
                    if (flag) {
                        var moveX = event.clientX;
                        var scrollX = moveX - downX;
                        if (scrollX < 0 && scrollLeft > 0) {
                            $(container).scrollLeft(scrollLeft - scrollX)
                        }
                        else {
                            $(container).scrollLeft(scrollLeft - scrollX)
                        }
                    }
                });
                //鼠标释放
                $(document).on("mouseup", function () {
                    console.log('mouseup')
                    flag = false;
                });
                /**
                 * 注意:与 mouseout 事件不同,mouseleave 事件只有在鼠标指针离开被选元素时被触发,mouseout 事件在鼠标指针离开任意子元素时也会被触发。参见页面底部演示实例。
                 * 所以:如果mouseout的子元素存在溢出,并添加了超出加滚动,那么刚进入也会触发该事件,所以这里就不能使用。
                 * */
                //鼠标移出元素
                $(container).on("mouseleave", function (event) {
                    console.log('mouseleave', event.pageX, document.body.offsetWidth)
                    // flag = false;
                    if (event.pageX < 0 || event.pageX > document.body.offsetWidth) {
                        console.log('在元素上移出')
                        flag = false;
                    }
                });
            }

            dragMoveX(".JDLMtabList");



            this.contanier.on('click', '.activity-card-tips-btn', function () {
                layer.open({
                    title: '活动规则',
                    content:
                        `<div class="edit-content">
                            <div>1.购物补贴<b class="red">1天内</b>领取有效,7天内使用有效,具体金额以实际收到为准</div>
                            <div>2.购物补贴可在跳转至京东下单且选择支付时使用</div>
                            <div>3.下单前请检查是否勾选购物补贴,以免影响优惠使用</div>
                            <div>4.使用购物补贴下单,亦可获得平台返利</div>
                            <div>5.若有疑惑,可咨询客服解答</div>
                        </div>`,
                    skin: 'prompt-topping-tips',
                    area: ['90%', 'auto'],
                    closeBtn: 0    // 是否显示关闭按钮
                    , anim: 5 //动画类型
                    , btn: ['知道了'],
                    cancel: function (index, layero) {
                        layer.close()
                    }
                })
            })
        }
        getData(isPageTurning) {
            let that = this;
            return new Promise((resolve, reject) => {
                $.ajax({
                    type: "get",
                    url: " /handler/GetPopularGoodsHandler.aspx",
                    contentType: "application/x-www-form-urlencoded",
                    data: {
                        tag: this.tag,
                        pageSize: this.pageSize,
                        page: (() => { let page = this.page; this.page++; return page })(),
                     
                    },
                    dataType: "json",
                    success: (result, status, xhr) => {
                        if (result.success) {
                            that.pageTemp++
                            resolve(result, status, xhr)
                        } else {
                            this.PopularGoodList = [];
                            this.Tags = [];
                            this.Items = [];
                            reject(xhr, status, xhr)
                        } 
                    },
                    error: (xhr, status, error) => {
                        this.PopularGoodList = [];
                        this.Tags = [];
                        this.Items = [];
                        reject(xhr, status, error)
                    },
                    complete: (xhr, status) => {
                        
                    }
                })
            })
        }
        refreshDom() {

        }
        writeDom(isPageTurning) {
            if (isPageTurning) {
                this.writeContent(isPageTurning);
            } else {
                this.writePopularGoodList();
                this.writeTags();
                this.writeContent();
            }
           
        }
        writeContent(isPageTurning) {
            let fragment = document.createDocumentFragment();
            this.Items.forEach(function (v) {
                if (!v.Id) {
                    SLS_CLIENT.addLog({
                        key: 'no-commodity-id',
                        val: '出现商品没有商品id的情况',
                        url: ajaxUrl,
                        json: {
                            json: 'json'
                        }
                    })
                }
                var coupLink = "";
                if (v.CouponLink) {
                    coupLink = v.CouponLink;
                }
                else if (v.SearchId) {
                    coupLink = v.SearchId;
                }
                let onclickAction = `goodsClick('${v.MallType}','${v.Id}','${coupLink}','${v.IdSign}','${v.OriPrice}','${v.CouponAmount}','${v.Gift}','${v.Price}','${v.Name}')`;
                var imgurl = v.Image ? v.Image : "<%=Thsb.Config.ConfigInfo.OssStatic.Domain %>/image/shangpinzhanwei.png";
                let itemDom = $(`
                    <div class="JDLMcontent_item" οnclick="${onclickAction}">
                        <img loading="lazy" src="${imgurl}" οnerrοr="this.src='<%=Thsb.Config.ConfigInfo.OssStatic.Domain %>/image/shangpinzhanwei.png'" />
                        <div class="JDLMcontent_item_right">
                            <span class="JDLMcontent_item_right_title"> 
                                <span class="source-tag iconfont"></span>
                                <span>${v.Name}</span>
                            </span>
                            <div class="JDLMcontent_item_right_middle">
                                <div class="rebate-card">${v.Jifen}元</div>
                                ${v.CouponAmount ? `<div class="certificate-card">${v.CouponAmount}元</div>` : ``}
                                ${v.Gift ? `<div class="activity-gift-card">${v.Gift}元</div>` : ``}
                            </div>
                            <div class="JDLMcontent_item_right_bottom">
                                <div class="price-group">
                                    <div class="price">${v.Price == v.OriPrice ? "热卖价" : v.CouponAmount ? '券后价' : '优惠价'}¥<span class="">${v.Price}</span></div>
                                    ${v.Price == v.OriPrice ? `` : `<div class="old-price">¥<span >${v.OriPrice}</span></div>`}
                                </div>
                            </div>
                            <div class="JDLMcontent_item_right_footer">
                                ${v.OrderCount == '0' ? `` : ` <div class="people-num">${v.Source == '京东' || v.Source == '淘宝' ? '月' : ''}${v.OrderCount}人付款</div>`}
                            </div>
                        </div>
                    </div>
                `);
                switch (v.MallDetailType) {
                    case 1:
                        itemDom.find('.source-tag').html('&#xe719;');
                        break;
                    case 2:
                        itemDom.find('.source-tag').html('&#xe744;');
                        break;
                    case 3:
                        itemDom.find('.source-tag').html('&#xe71b;');
                        break;
                    case 4:
                        itemDom.find('.source-tag').html('&#xe748;');
                        break;
                    case 5:
                        itemDom.find('.source-tag').html('&#xe71a;');
                        break;
                    case 6:
                        itemDom.find('.source-tag').html('&#xe746;');
                        break;
                    case 7:
                        itemDom.find('.source-tag').html('&#xe747;');
                        break;
                }
                $(fragment).append(itemDom)
            });
            if (!isPageTurning) {
                this.contentContanier.empty();
            }
            this.contentContanier.append(fragment);
        }
        writeTags() {
            if (this.Tags && this.Tags.length) {
                this.tagContanier.show();
                this.tagContanier.empty();
                let fragment = document.createDocumentFragment();
                this.Tags.forEach((v,index) => {
                    let dom = $(`<div class="${v.IsSelect ?'active':''} JDLMtabList-div">
                        ${v.Tag}
                        <span class="${v.IsSelect ? 'line' : ''}"></span>
                    </div>`)
                    $(fragment).append(dom);
                    if (v.IsSelect) {
                        this.index = index;
                    }
                })
                this.tagContanier.append(fragment);
            } else {
                this.tagContanier.hide();
                this.tagContanier.empty();
            }
        }
        writePopularGoodList() {
            if (this.PopularGoodList && this.PopularGoodList.length) {
                this.cardContanier.show();
                this.cardContanier.empty();
                let swiperContanier = $(`
                <div class="hot-sales-card-contanier">
                    <div class="hot-sales-swiper-wrapper">
                        <div class="swiper-wrapper">
                            
                        </div>
                    </div>
                </div>
                <div class="swiper-wrapper-switch"></div>
                `)
                let swiperWrapper = swiperContanier.find('.swiper-wrapper');
                let sweiperSlide;
                this.PopularGoodList.forEach((v, index) => {
                    if (index % 4 == 0) {
                        sweiperSlide = $(`<div class="swiper-slide"></div>`);
                        swiperWrapper.append(sweiperSlide);
                    }

                    let imgurl = v.Image ? v.Image : "<%=Thsb.Config.ConfigInfo.OssStatic.Domain %>/image/shangpinzhanwei.png";
                    let coupLink = "";
                    if (v.CouponLink) {
                        coupLink = v.CouponLink;
                    }
                    else if (v.SearchId) {
                        coupLink = v.SearchId;
                    }
                    let onclickAction = `goodsClick('${v.MallType}','${v.Id}','${coupLink}','${v.IdSign}','${v.OriPrice}','${v.CouponAmount}','${v.Gift}','${v.Price}','${v.Name}')`;

                    sweiperSlide.append($(
                        `<div class="hot-sales-swiper-card"  οnclick="${onclickAction}">
                            <div class="img-contanier"><img src="${imgurl}" loading="lazy"/></div>
                            ${v.Gift ?
                            `<div class="hot-sales-swiper-tag gift-card">
                                <div class="gift-card-box">
                                    <div class="gift-card-label">礼金</div>
                                    <div class="gift-card-val">${v.Gift}元</div>
                                </div>
                            </div>` :
                            `<div class="hot-sales-swiper-tag">
                                <span class="iconfont">&#xe754;</span>
                                <span>${v.Source == '京东' || v.Source == '淘宝' ? '月销' : '总销'}${v.OrderCount}</span>
                            </div>`}
                            
                        </div>`
                    ))
                })
                this.cardContanier.append(swiperContanier);
                if (this.PopularGoodList.length > 4) {
                    this.swiper = new Swiper('.hot-sales-swiper-wrapper', {
                        autoplay: {
                            delay: 6000,//1秒切换一次
                            pauseOnMouseEnter: true,
                            disableOnInteraction: false,
                        },
                        loop: true,
                        freeMode: false,
                        enabled: false,
                        pagination: {
                            el: '.swiper-wrapper-switch',
                            clickable: true,
                        },
                    })
                    // https://www.swiper.com.cn/api/pagination/69.html 4x版本,文档自读
                }

            } else {
                this.cardContanier.hide();
                this.cardContanier.empty();
            }
            
        }
        getQueryVariable(variable) {
            var urlParameter = window.location.search;
            var query = urlParameter.substring(1);
            var vars = query.split("&");
            for (var i = 0; i < vars.length; i++) {
                var index = vars[i].indexOf('=');
                if (vars[i].substr(0, index) == variable) {
                    return decodeURIComponent(vars[i].substr(index + 1))
                }
            }
            return '';
        }
    }
    let pageConceptContanier = new Init();
    var isPageHide = false;
    //window.addEventListener('pageshow', function () {
    //    if (isPageHide) {
    //        pageConceptContanier = new Init();
    //        return
    //    }
    //});
    //window.addEventListener('pagehide', function (e) {
    //    isPageHide = true;
    //});
</script>
<script>

</script>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值