开发功能归纳

例子都有对应测试数据可以跑通查看


1.搜索跳转,判空后再执行后续动作

// 回车动作
$('.check_empty').off("keydown").on("keydown", function (e) {
    let {
        keyCode
    } = e;

    let p = $(this).closest('.search-form')

    if (keyCode == 13) {
        $(this).val($(this).val().trim())

        let val = p.find('.check_empty').val()
        let reg = /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/;
        flag = reg.test(val);
        if (flag) {
            // $(this).attr("type", "submit");
        } else {
            return false
        }
    }
});
// 点击搜索动作
$('.search-btn').off("click").on("click", function (e) {
    let p = $(this).closest('.search-form')
    let val = p.find('.check_empty').val()
    let reg = /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/;
    flag = reg.test(val);
    if (flag) {
        $(this).attr("type", "submit");
    }
});

2.自定义下拉框,点击后需要赋值给匹配name名的input存值

// 回车动作
$('.j-value').off("click").on("click", function (e) {
    let p = $(this).closest('.j-form');

    let meSubmit = p.is('.meSubmit') || false; // 手动触发
    let key = $(this).attr('data-key');// name 名
    let newval = $(this).attr('data-value');// 点击的value
    let target = p.find(`input[name=${key}]`);// 最后form表单提交的value  input标签
    let targetView = p.find(`div[name=${key}]`);// 显示作用的文本标签
    target.attr('value', newval);
    targetView.text(newval);
    if (!meSubmit) {
        $('.j-form').submit();
    } else {
        $(document).click();
    }
});

3.同级标签切换类名逻辑

参考页面

/*

onlyoneInit() => 初始化配置
click或者hover事件初始化,通过循环initArr 区分hover和click 对应的dom名称,再分别进行对应的初始化处理
onlyOneHandleDom() => 封装了大部分相同的逻辑代码 

*/
onlyoneInit();

// 初始化事件
function onlyoneInit() {
    // console.time();
    // 配置
    let initArr = [{ // 鼠标hover事件
            evenType: 'hover',
            bind: '.hover-onlyone', //事件元素
            bind_parent: '.hover-onlyone-parent', //事件元素li的上级
            bind_son: '.hover-onlyone-li', //事件元素
            bind_borther: '.hover-onlyone-brother', //联动事件元素
            targetClass: '.endadd', //如果存在则变为最后的添加类名元素  
            alsoadd: '.alsoadd', //一起添加行为类名的元素 
            addClass: 'active', //行为类名 
            animation_type: '.isslide', // 动画类型 slideUp slideDown 
            animation_dom: '.togglebox', // 动画切换的dom 
            returnMob: '.mobileReturn', //手机端停止触发
            saveClass: '.endSaveClass', //hover移出的时候不改变行为
        },
        { // 点击事件
            evenType: 'click',
            bind: '.click-onlyone', //事件元素
            bind_parent: '.click-onlyone-parent', //事件元素li的上级
            bind_son: '.click-onlyone-li', //事件元素
            bind_borther: '.click-onlyone-brother', //联动事件元素
            targetClass: '.endadd', //如果存在则变为最后的添加类名元素  
            alsoadd: '.alsoadd', //一起添加行为类名的元素 
            addClass: 'active', //行为类名 
            animation_type: '.isslide', // 动画类型 slideUp slideDown 
            animation_dom: '.togglebox', // 动画切换的dom 
            returnMob: '.mobileReturn', //手机端停止触发
            saveClass: '.endSaveClass', //hover移出的时候不改变行为
        },
    ]
    // 循环配置
    for (let i = 0; i < initArr.length; i++) {
        let item = initArr[i];
        let {
            evenType,
            bind,
            bind_parent
        } = item;
        if ($(bind_parent).length == 0) continue

        switch (evenType) {
            case 'hover':
                $(bind).hover(function () {
                    onlyOneHandleDom(item, $(this))
                });
                break;
            case 'click':
                $(bind).off("click").on("click", function (myeven) {
                    onlyOneHandleDom(item, $(this))
                    myeven.stopPropagation();
                });
                break;
        }
    }
}



// 添加类名逻辑
function onlyOneHandleDom(myconfig, that) {
    let {
        evenType,
        bind,
        bind_parent,
        bind_son,
        bind_borther,
        targetClass,
        alsoadd,
        addClass,
        animation_type,
        animation_dom,
        returnMob,
        saveClass
    } = myconfig;


    let ismobile = that.closest(bind_parent).is(returnMob); //mobile端不执行
    let bind_index = that.closest(bind_son).index();
    let save = that.closest(bind_parent).is(saveClass); //保持类名
    let p = that.closest(bind_parent); // 父级dom
    let son = p.find(bind_son).find(targetClass); // 父级下的son dom集合
    let brother = p.find(bind_borther).find(targetClass); // 父级下与son联动的brother dom集合


    let target = that.closest(bind_son).find(targetClass); // 最后进行切换的dom
    let brothertarget = p.find(bind_borther).eq(bind_index).find(targetClass); // 最后进行切换的联动brother元素

    // 动画切换模式
    let isAnitoggle = that.closest(bind_parent).is(animation_type); //slideup slidedown切换
    let ani_target_list = p.find(bind_son).find(animation_dom);
    let ani_brothertarget_list = p.find(bind_borther).find(animation_dom);
    let ani_target_me = that.closest(bind_son).find(animation_dom);
    let ani_brothertarget_me = p.find(bind_borther).eq(bind_index).find(animation_dom);

    // also添加的一个元素
    let also = p.find(bind_son).find(alsoadd);
    let brother_also = p.find(bind_borther).find(alsoadd);
    let also_target = that.closest(bind_borther).find(alsoadd); // 最后一起添加行为类名的元素 dom
    let brother_also_target = p.find(bind_borther).eq(bind_index).find(alsoadd); // 最后brother元素一起添加行为类名的dom


    let w = $(window).width();
    if (w < 1024) {
        if (ismobile) return
    }


    // 最后切换的元素dom
    if (target.length == 0) { // hoveradd类名不存在 则重新赋值target和son
        target = p.find(bind_son).eq(bind_index);
        son = p.find(bind_son);
    }
    // 最后联动切换的元素dom
    if (brothertarget.length == 0) { // hoveradd类名不存在 则重新赋值
        brothertarget = p.find(bind_borther).eq(bind_index)
        brother = p.find(bind_borther);
    }

    let isadd = target.is(`.${addClass}`);
    // console.log('当前',target,bind_index)






    if (isadd) { // 已经有了行为类名



    } else { // 还没有行为类名
        // console.log('我还没有',bind_index)
        son.removeClass(addClass);
        if (save) {
            target.addClass(addClass);
        } else {
            target.toggleClass(addClass);
        }

        if (also.length > 0) {
            also.removeClass(addClass);
            if (save) {
                also_target.addClass(addClass);
            } else {
                also_target.toggleClass(addClass);
            }
        }

        if (isAnitoggle) {
            ani_target_list.removeClass(addClass).stop().slideUp()
            if (save) {
                ani_target_me.addClass(addClass).stop().slideDown();
            } else {
                ani_target_me.toggleClass(addClass).stop().slideToggle();
            }

        }
    }




    if (brother.length > 0) {
        if (isadd) {
            if (save) {
                // console.log(232)
            } else {
                brother.removeClass(addClass);
                if (brother_also.length > 0) {
                    brother_also.removeClass(addClass);
                }

                if (isAnitoggle) {
                    ani_brothertarget_list.removeClass(addClass).stop().slideUp()
                }
            }

        } else {
            brother.removeClass(addClass);
            if (save) {
                brothertarget.addClass(addClass);
            } else {
                brothertarget.toggleClass(addClass);
            }

            if (brother_also.length > 0) {
                brother_also.removeClass(addClass);
                if (save) {
                    brother_also_target.addClass(addClass);
                } else {
                    brother_also_target.toggleClass(addClass);
                }
            }

            if (isAnitoggle) {
                ani_brothertarget_list.removeClass(addClass).stop().slideUp()
                if (save) {
                    ani_brothertarget_me.addClass(addClass).stop().slideDown();
                } else {
                    ani_brothertarget_me.toggleClass(addClass).stop().slideToggle();
                }

            }
        }
    }

    // 如果是点击事件 并且切换类型是动画  slideUp和slideDown
    if (evenType == 'click' && isAnitoggle) {
        // 点击页面重置对应的slideUp
        $(document).off("click").on("click", function (e) {
            let Doctarget = $(e.target);
            let hasadd = son.is(`.${addClass}`);

            if (Doctarget.closest(bind_son).length == 0) {
                // console.log(Doctarget.closest(bind_son).length,'DoctargetDoctarget')
                // console.log(hasadd,'hasadd')

                if (hasadd) {
                    if (save) {} else {
                        // li.removeClass('active').find('.togglebox').stop().slideUp();
                        // li.find('.alosadd').removeClass('active');
                        son.removeClass(addClass);
                        if (also.length > 0) {
                            also.removeClass(addClass);
                        }
                        ani_target_list.removeClass(addClass).stop().slideUp()

                        if (brother.length > 0) {
                            brother.removeClass(addClass);
                            if (brother_also.length > 0) {
                                brother_also.removeClass(addClass);
                            }
                            ani_brothertarget_list.removeClass(addClass).stop().slideUp()
                        }
                    }
                }
            };
            e.stopPropagation();
        })
    }

}


4.页面滚动某个距离给标签添加类名

// 鼠标往下滚动时添加类名 往上时去除类名
function scrollHeaderInit(e) {
    let {
        bind_list, //符合条件后需要添加类名的DOM元素集合
        break_handle, // 如果返回true 则不执行后面的逻辑
        append_handle, // 追加函数处理 执行其他自定义操作
        up_classname, // 上滑时添加的类名
        down_classname, // 上滚时添加的类名
        scrolling_classname, // 滚动中添加的类名
        init_num, // 大于这个值开始执行滚动事件的处理逻辑
    } = e;

    let scroll_start = 0,
        scroll_end = 0,
        scroll_can = true,
        scroll_task = null;
    // debugger

    $(window).scroll(function () {
        // clearTimeout(scroll_task);
        // scroll_task = setTimeout(function () {
        //     scroll_can = true;
        // }, 50);
        // if (!scroll_can) return
        // scroll_can = false;

        // console.log({
        //     scroll_start,
        //     scroll_end,
        //     init_num
        // })
        if (break_handle && break_handle()) return
        if (scroll_end < init_num) {
            for (let index = 0; index < bind_list.length; index++) {
                let addTarget = bind_list[index];
                $(addTarget).removeClass(scrolling_classname);
                $(addTarget).removeClass(down_classname);
                $(addTarget).removeClass(up_classname);


            }

        } else {

            if (scroll_end >= scroll_start) {
                // 往下滚
                scroll_start = scroll_end;
                for (let index = 0; index < bind_list.length; index++) {
                    let backdata = {
                        'type': 'down'
                    };
                    let addTarget = bind_list[index];
                    $(addTarget).addClass(scrolling_classname);
                    $(addTarget).addClass(down_classname);
                    $(addTarget).removeClass(up_classname);
                    append_handle && append_handle(backdata);
                }
            } else {
                // 往上滑
                scroll_start = scroll_end;
                for (let index = 0; index < bind_list.length; index++) {
                    let backdata = {
                        'type': 'up'
                    };
                    let addTarget = bind_list[index];
                    $(addTarget).addClass(scrolling_classname);
                    $(addTarget).addClass(up_classname);
                    $(addTarget).removeClass(down_classname);
                    append_handle && append_handle(backdata);
                }
            }
        }

        // if (scroll_start > scroll_end && scroll_end > 300) {
        //     $($classname).addClass(down_classname);
        // } else {
        //     $($classname).removeClass(down_classname);
        // }
    });

}

// bind_list, //符合条件后需要添加类名的DOM元素集合
// break_handle, // 如果返回true 则不执行后面的逻辑
// up_classname, // 上滑时添加的类名
// down_classname, // 上滚时添加的类名
// scrolling_classname, // 滚动中添加的类名
// init_num, // 大于这个值开始执行滚动事件的处理逻辑

// 导航条在鼠标滚动事件
scrollHeaderInit({
    bind_list: ['.nav-header'],
    up_classname: 'isup',
    down_classname: 'isdown',
    scrolling_classname: 'isscrolling',
    init_num: 1,
    break_handle: function () {
        let break_flag = $('.nav-hader-content').is('.isshowmap');
        // console.log(break_flag, 'break_flag')
        return break_flag
        // return false
    }
})

5.监听鼠标滚轮 滚动事件(需要引入jquery.mousewheel.min.js)


// ele 获取滚轮的条件行程值
// judgeHandle 滑轮滑动调函数
// handle 执行完成回调函数

// backMouse({
//     ele: $(pageitem[nowIndex]),
//     judgeHandle: function(e) {
//         let {
//             i,
//             max,
//             type
//         } = e;
//         $(movebox).css('transform',
//             `translateY(-${(myh / howmove) * i}px)`)

//         libox.eq(Math.floor(i / howmove)).addClass('active').siblings()
//             .removeClass('active');
//         // console.log(max / (i * howmove))
//         // console.log(max % i)
//     },
//     handle: function(e) {
//         // console.log('yunxu')
//         let {
//             type
//         } = e;
//         pagefull.mousewheel.enable();
//         if (type == 'up') {
//             pagefull.slidePrev();
//         } else {
//             pagefull.slideNext();
//         }
//     }
// });

var mouseTask = null;
// mac的鼠标会滚动很大 通过定时器修改canChange实现防抖
var canChange = true;

function backMouse(e) {
    let {
        judgeHandle,
        handle,
        ele
    } = e;

    console.log(ele)

    // $('.mouseEvent').each(function(i, ele) {
    let sT = $(window).scrollTop(),
        metop = ele.offset().top,
        nowmouse = ele.attr('data-nowmouse'),
        endmouse = ele.attr('data-endmouse'); //需要滚动多少次鼠标才执行结束函数
    let meCall = Boolean(Number(ele.attr('isbackMouse'))) || false; // 手动调用

    let readyGo;

    if (meCall) {
        readyGo = meCall;
    } else if (sT > metop) {
        readyGo = true;
    }

    if (readyGo) {
        let i = nowmouse;
        let max = endmouse; //最大滑动次数
        // let len = 4;
        $(window).unbind('mousewheel');
        $(window).mousewheel(function (even) {
            if (!canChange) {
                return
            } else {
                setTimeout(() => {
                    canChange = true;
                }, 30);
            }
            if (even.deltaY < 0) { // 往下滚动
                if (i == max) {
                    canChange = true;
                    handle({
                        type: 'down'
                    });
                    $(window).unbind('mousewheel');
                    ele.attr('data-nowmouse', i);
                } else {
                    if (mouseTask) {
                        clearTimeout(mouseTask);
                        mouseTask = null;
                    }

                    mouseTask = setTimeout(() => {
                        i++;
                        canChange = false;
                        ele.attr('data-nowmouse', i);
                        judgeHandle({
                            i,
                            max,
                            type: 'down'
                        })
                    }, 20);


                }

                console.log(i, '下')
            } else { // 往上滚动
                if (i == 0) {
                    canChange = true;
                    handle({
                        type: 'up'
                    });
                    $(window).unbind('mousewheel');
                    ele.attr('data-nowmouse', i);
                } else {

                    if (mouseTask) {
                        clearTimeout(mouseTask);
                        mouseTask = null;
                    }
                    mouseTask = setTimeout(() => {
                        i--
                        canChange = false;
                        ele.attr('data-nowmouse', i);
                        judgeHandle({
                            i,
                            max,
                            type: 'up'
                        })
                    }, 20);


                }
                console.log(i, '上')
            }
        });
    }
    // })
}

6.swiper-点击按钮实现开启或者停止自动轮播

// swiper初始化
// init: function() {
//     pause_event({
//         swiper: this,
//         eventClass: '.green-thumbs .com-pause'
//     });
//     this.emit('slideChangeTransitionStart');
// },

// 点击swiper暂停按钮 
function pause_event(e) {
    let {
        eventClass,
        swiper
    } = e;

    if ($(eventClass).length == 0) return
    $(eventClass).on('click', function () {
        if (swiper.autoplay.running) {
            swiper.autoplay.stop();
            $(this).addClass('canplay');
        } else {
            swiper.autoplay.start();
            $(this).removeClass('canplay');
        }
    })
}

7.swiper 设置进度条

// html标签部分
// pagination: {
//     el: ".swiper-pagination-green",
//     type: "custom",
//     renderCustom: function(swiper, current, total) {
//         let n = current < 9 ? `0${current}` : current;
//         let t = total < 9 ? `0${total}` : total;

//         return `
//         <span class="now-num fz14 color1 fw700" data-num="${current}">${n}</span>
//         <span class="total-num fz14 color24 fw700" data-total="${total}">${t}</span>`
//     }
// },

// js部分
// slideChangeTransitionStart: function() {
//     getNumSwiper({
//         swiper: this,
//         numbox: '.green-thumbs .com-num',
//         pressbox: '.green-thumbs .com-progress .proess'
//     });
// },
function getNumSwiper(e) {
    let {
        swiperClass,
        swiper,
        numbox,
        pressbox
    } = e;

    let n = $(numbox).find('.now-num').attr('data-num');
    // let n = swiper.activeIndex + 1;
    let t = $(numbox).find('.total-num').attr('data-total');
    let p = '100%';
    // console.log(n, t);
    if (t > 0) {
        p = n / t * 100 + '%'
    }
    $(pressbox).css('width', p)
    // console.log(numbox);
    // console.log(pressbox);
    // console.log(swiper.progress, "进度");
    // console.log(swiper.slides.length);
    // console.log(swiper.activeIndex, "当前index");
    // console.log($(swiper.$el).find('.swiper-slide'), "$el");
    // console.log(swiper.width, "width");
    // console.log(swiper.isEnd);
    // console.log($(swiperClass).length);
}

8.获取数据类型

function gettype(o) {
    let result = Object.prototype.toString.call(o).slice(8, -1);
    if (result === 'Null') {
        return null
    } else if (result === 'Undefined') {
        return undefined;
    } else {
        return result;
    }
}

9.数据判空

// 数据类型判空
function objJudge(arg) {
    let result = Object.prototype.toString.call(arg).slice(8, -1);
    switch (result) {
        case 'Undefined':
            return false
            break;
        case 'Null':
            return false
            break;
        case 'Object':
            return JSON.stringify(arg) !== '{}'
            break;
        case 'Array':
            return arg.length !== 0
            break;
        case 'String':
            return arg !== '';
            break;
        case 'Number':
            return true
            break;
        case 'Boolean':
            return arg
            break;
    }
}

11.遍历数据返回以及遍历数据查找对应数据




let post_data_init = {
    myinit: function (e) {
        let {
            obj,
            current_name,
            end_value,
            total_name,
            data,
            isend,
            islooping
        } = e;
        if (isend) {
            data[`${total_name}`] = end_value
            // console.log({
            //     current_name,
            //     end_value,
            //     data,
            //     total_name,
            //     data,
            //     isend
            // });
        } else {
            if (islooping) total_name += current_name;
            // console.log(current_name, 'myname')
            // if (current_name == '[myname2]') {

            // }
            let obj_type = Object.prototype.toString.call(obj).slice(8, -1);
            switch (obj_type) {
                case 'Undefined':
                    this.myinit({
                        current_name,
                        end_value: obj,
                        total_name,
                        data,
                        isend: true
                    })
                    break;
                case 'Null':
                    this.myinit({
                        current_name,
                        end_value: obj,
                        total_name,
                        data,
                        isend: true
                    })
                    break;
                case 'String':
                    this.myinit({
                        current_name,
                        end_value: obj,
                        total_name,
                        data,
                        isend: true
                    })
                    break;
                case 'Number':
                    this.myinit({
                        current_name,
                        end_value: obj,
                        total_name,
                        data,
                        isend: true
                    })
                    break;
                case 'Boolean':
                    this.myinit({
                        current_name,
                        end_value: obj,
                        total_name,
                        data,
                        isend: true
                    })
                    break;
                case 'Array':
                    for (let i = 0; i < obj.length; i++) {
                        this.myinit({
                            obj: obj[i],
                            current_name: `[${i}]`,
                            end_value,
                            total_name,
                            data,
                            isend,
                            islooping: true
                        })
                    }
                    break;
                case 'Object':
                    for (let k in obj) {
                        this.myinit({
                            obj: obj[k],
                            current_name: `[${k}]`,
                            end_value,
                            total_name,
                            data,
                            isend,
                            islooping: true

                        })

                    }
                    break;
            }
        }
        return data


    },
    find_to_handle: function (e) {
        let {
            obj,
            attr_name,
            handle
        } = e;
        if (!handle(e)) {
            if (gettype(obj) == 'Array') {
                for (let i = 0; i < obj.length; i++) {
                    this.find_to_handle({
                        obj: obj[i],
                        handle
                    });
                }
            } else if (gettype(obj) == 'Object') {
                for (let k in obj) {
                    // console.log(obj[k], 'obj[k]')
                    this.find_to_handle({
                        obj: obj[k],
                        attr_name: k,
                        handle
                    });

                }
            }
        }


    }
}


let test_obj = {
    "key1": "abc", // 字符串类型
    "key2": 1234, // Number
    "key3": [1234, "21341", "53"], // 数组
    "key4": { // json 类型
        "key4_1": 12,
        "key4_2": "kkk",
        "key4_3": { // json 类型
            "key4_1": 12,
            "key4_2_qwe": ["kkk"]
        }
    }
}

let newData = post_data_init.myinit({
    obj: test_obj,
    data: {},
    total_name: 'content',
    isend: false,
    islooping: false
})

console.log(newData)

{
	"content[key1]": "abc",
	"content[key2]": 1234,
	"content[key3][0]": 1234,
	"content[key3][1]": "21341",
	"content[key3][2]": "53",
	"content[key4][key4_1]": 12,
	"content[key4][key4_2]": "kkk",
	"content[key4][key4_3][key4_1]": 12,
	"content[key4][key4_3][key4_2_qwe][0]": "kkk"
}


let newobj = [];
let newData2 = post_data_init.find_to_handle({
    obj: test_obj,
    handle: function (e) {
        let {
            obj,
            attr_name,
            handle
        } = e;

        if (gettype(obj) && gettype(obj.key4_2_qwe)) {
            //
            newobj.push(obj.key4_2_qwe)
        } else {
            return false
        }
    }
})
console.log(JSON.stringify(newobj))
[["kkk"]]

12.把相同楼名归类后,下属楼层放入一个list中


var dataarr = [{
    "test_id": "420",

    "test_building": "C栋",

    "test_floor_text": "1层",


}, {
    "test_id": "420",

    "test_building": "B栋",

    "test_floor_text": "1层",


}, {
    "test_id": "420",

    "test_building": "a栋",

    "test_floor_text": "1层",


}, {

    "test_id": "420",

    "test_building": "14栋",

    "test_floor_text": "1层",


}, {
    "test_id": "252",

    "test_building": "7",

    "test_floor_text": "5",




}, {
    "test_id": "251",

    "test_building": "17栋",

    "test_floor_text": "6",




}, {
    "test_id": "420",

    "test_building": "X栋",

    "test_floor_text": "1层",


}, {
    "test_id": "250",

    "test_building": "7栋",

    "test_floor_text": "5",




}, {
    "test_id": "223",

    "test_building": "2栋",

    "test_floor_text": "6楼",




}, {
    "test_id": "205",

    "test_building": "9栋",

    "test_floor_text": "1楼",




}, {
    "test_id": "204",

    "test_building": "8栋",

    "test_floor_text": "1楼",




}, {
    "test_id": "203",

    "test_building": "8栋",

    "test_floor_text": "3楼",




}, {
    "test_id": "150",

    "test_building": "2栋",

    "test_floor_text": "3楼",




}, {
    "test_id": "149",

    "test_building": "2栋",

    "test_floor_text": "5楼",




}, {
    "test_id": "148",

    "test_building": "2栋",

    "test_floor_text": "5楼及6楼",




}, {
    "test_id": "147",

    "test_building": "4栋",

    "test_floor_text": "1栋",




}, {
    "test_id": "146",

    "test_building": "2栋",

    "test_floor_text": "2楼",




}, {
    "test_id": "145",

    "test_building": "5栋",

    "test_floor_text": "1楼",




}, {
    "test_id": "144",

    "test_building": "1栋",

    "test_floor_text": "2楼",




}, {
    "test_id": "143",

    "test_building": "2栋",

    "test_floor_text": "4楼",




}, {
    "test_id": "142",

    "test_building": "4栋",

    "test_floor_text": "1楼",




}, {
    "test_id": "141",

    "test_building": "1栋",

    "test_floor_text": "1楼",




}, {
    "test_id": "140",

    "test_building": "3栋",

    "test_floor_text": "4楼",




}, {
    "test_id": "139",

    "test_building": "3栋",

    "test_floor_text": "2楼",




}, {
    "test_id": "138",

    "test_building": "7栋",

    "test_floor_text": "5楼",




}, {
    "test_id": "137",

    "test_building": "3栋",

    "test_floor_text": "5楼",




}, {
    "test_id": "136",

    "test_building": "2栋",

    "test_floor_text": "7楼",




}, {
    "test_id": "135",

    "test_building": "7栋",

    "test_floor_text": "3楼",




}, {
    "test_id": "134",

    "test_building": "2栋",

    "test_floor_text": "1楼",




}, {
    "test_id": "133",

    "test_building": "5栋",

    "test_floor_text": "2楼",




}, {
    "test_id": "132",

    "test_building": "7栋",

    "test_floor_text": "4楼",




}, {
    "test_id": "131",

    "test_building": "3栋",

    "test_floor_text": "3楼",




}, {
    "test_id": "130",

    "test_building": "7栋",

    "test_floor_text": "2楼",




}, {
    "test_id": "129",

    "test_building": "3栋",

    "test_floor_text": "1楼",


}];


/*
    checkPush 检查重复项 
    {
        7楼:{index :0 },
        4楼:{index :12},
    }
    pre => []; 空数组为默认值,最后输出的数组
    next => 每一项

    let o = {
        test_building: 7楼,
        mylist:[]
    };
    i++; 记录pre数组的索引
*/

function findKeyAndPushList(e) {
    let {
        arr,
        findkey,
        pushkey,
        listname
    } = e;

    let checkPush = {};
    let i = 0;
    return arr = arr.reduce((pre, next) => {
        let k = next[findkey];
        if (!checkPush[k]) {
            checkPush[k] = {
                index: i
            };
            let o = {};
            o[findkey] = k;
            o[listname] = [];
            pre.push(o)
            i++;
        }
        pre[checkPush[k].index][listname].push(next);
        // [checkPush[k].index] => 在checkPush对象中找到对应的 findkey后获取他的 index value 索引
        // pre[索引][listname] => pre[索引].mylist push当前项 next进入下级数组 

        return pre;
    }, []);
}

let backarr = findKeyAndPushList({
    arr: dataarr,
    findkey: 'test_building',
    pushkey: 'test_floor_text',
    listname: 'mylist',
}).sort((a, b) => {
    // 如果字母开头则按字母正序
    if (isNaN(parseInt(a.test_building)) && isNaN(parseInt(b.test_building))) {
        let x = a.test_building.slice(0, 1).toUpperCase()
        let y = b.test_building.slice(0, 1).toUpperCase()
        return x < y ? -1 : x > y ? 1 : 0;
    } else {
        // 字母统一在数字前面
        // 数字按正序
        let x = isNaN(parseInt(a.test_building)) ? 0 : parseInt(a.test_building);
        let y = isNaN(parseInt(b.test_building)) ? 0 : parseInt(b.test_building);
        return x - y;
    }

})

backarr.forEach(ele => {
    if (ele.mylist.length > 1) {
        ele.mylist.sort((c, d) => {
            // 数字按正序
            let xx = isNaN(parseInt(c.test_floor_text)) ? 0 : parseInt(c.test_floor_text);
            let yy = isNaN(parseInt(d.test_floor_text)) ? 0 : parseInt(d.test_floor_text)
            return xx - yy;
        })
    }
})

13.获取文本是否超出了行高


// 获取文本是否超出了行高
function getRow(e) {
    let {
        p,
        li,
        addName,
        addtarget,
        limit
    } = e;
    let list = $(p).find(li);
    // console.log(list);

    list.each(function (i, ele) {
        // let fs = $(this).css('font-size');
        let lh = parseFloat($(this).css('line-height'));
        let myh = $(this).height();

        let finalh = lh * limit; // 最高多高

        let row = Math.round(myh / parseFloat(lh)); // 现在几行
        // let top = $(this).scrollTop(); // 现在几行

        if (myh >= finalh) {
            // console.log($(p).find(addtarget).eq(i));
            // $(p).find(addtarget).eq(i).addClass(addName);
            $(this).closest(addtarget).addClass(addName);
            // debugger
        } else {
            // $(p).find(addtarget).addClass('bugou');
        }
        console.log({
            lh,
            myh,
            finalh,
            i,
            top
        })
        // debugger



    });
};
if ($('#mcoty').length > 0) {
    getRow({
        p: '#mcoty',
        li: '.swiper-slide .desc',
        limit: 5,
        addName: 'isoverflow',
        addtarget: '.seemore-p',
    })
}


13.页面滚动时,判断某个元素开始漏出


var scrollFlag = true;
// var windoShow = 0.7;
// var videoShow = 0.6;



function scroll_judge_element(e) {
    let {
        windoShow,
        videoShow,
        judge_suc,
        judge_fail
    } = e;
    if (!scrollFlag) return
    scrollFlag = false;
    let Wtop = $(window).scrollTop();
    let WH = $(window).height();
    let element = $(".judge_element");
    let my_top = element.offset().top;
    let my_height = element.height();
    if (my_height >= WH) {
        // 如果滚动距离小于 元素距离顶部的距离再加上自身的高度 -----比如视野看到元素 videoShow 漏出了 0.7  或者 1全部漏出
        // 如果滚动距离大于 元素距离顶部的距离再加上 窗口的高度 -----即看到元素隐藏了 windoShow 窗口多少就暂停播放
        var readyPlay = Wtop < my_top + (my_height * videoShow) && Wtop > my_top - (WH * windoShow) ? true : false;
        // console.log({
        // 	"滚动距离": Wtop,
        // 	'我离顶部距离': my_top,
        // 	'条件': my_top + WH + my_height,
        // })
    } else {
        // 要看到元素videoShow 部分 并且 没有开始隐藏元素videoShow部分 才播放
        // var readyPlay = Wtop + (WH * windoShow) > my_top && Wtop + WH < my_top + my_height ? true : false;
        var readyPlay = Wtop + WH > my_top + (my_height * videoShow) && Wtop < my_top + (my_height * videoShow) ? true : false;
        // console.log({
        // 	"滚动距离": Wtop,
        // 	'我离顶部距离': my_top,
        // 	'条件': my_top + (my_height * videoShow),
        // 	'条件2': my_top - (my_height * videoShow),
        // })
    }
    if (readyPlay) {
        judge_suc && judge_suc(element);
    } else {
        judge_fail && judge_fail(element);
    }
    scrollFlag = true;
}

scroll_judge_element({
    judge_suc: function (data) {
        console.log(data, 'suc');
    },
    judge_fail: function (data) {
        console.log(data, 'fail');
    }
})

$(window).scroll(function () {
    scroll_judge_element({
        windoShow: 0.5,
        videoShow: 0.5,
        judge_suc: function (data) {
            // console.log(data, 'suc');
            console.log('suc');
        },
        judge_fail: function (data) {
            console.log('fail');
        }
    })
});
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值