JS历理 优化base.js脚本

// 创建图片放大容器
document.writeln("<div id=\'outerdiv\' style=\'position:fixed;top:0;left:0;background:rgba(0,0,0,0.7);z-index:2;width:100%;height:100%;display:none;\'>");
document.writeln("<div id=\'innerdiv\' style=\'position:absolute;\'>");
document.writeln("<img id=\'bigimg\' style=\'border:5px solid #fff;\' src=\'\' /></div></div>");

layui.use(['form', 'layer', 'element'], function() {
    const form = layui.form;
    const layer = layui.layer;
    const element = layui.element;
    const $ = layui.jquery;

    // 图片放大方法
    function imgShow(outerdiv, innerdiv, bigimg, _this) {
        var src = _this.attr("src");
        $(bigimg).attr("src", src);
        $("<img/>").attr("src", src).load(function() {
            var windowW = $(window).width();
            var windowH = $(window).height();
            var realWidth = this.width;
            var realHeight = this.height;
            var imgWidth, imgHeight;
            var scale = 0.9;

            if (realHeight > windowH * scale) {
                imgHeight = windowH * scale;
                imgWidth = imgHeight / realHeight * realWidth;
                if (imgWidth > windowW * scale) {
                    imgWidth = windowW * scale;
                }
            } else if (realWidth > windowW * scale) {
                imgWidth = windowW * scale;
                imgHeight = imgWidth / realWidth * realHeight;
            } else {
                imgWidth = realWidth;
                imgHeight = realHeight;
            }

            $(bigimg).css("width", imgWidth);
            var w = (windowW - imgWidth) / 2 - 5;
            var h = (windowH - imgHeight) / 2 - 5;
            $(innerdiv).css({ "top": h, "left": w });
            $(outerdiv).fadeIn("fast");
        });

        $(outerdiv).click(function() {
            $(this).fadeOut("fast");
        });
    }

    // 删除数据方法
    window.setDelete = function(v, n) {
        var url = window.location.href;
        var path = encodeURIComponent(url);
        var value = window.atob(decodeURIComponent(v));
        var name = window.atob(decodeURIComponent(n));

        layer.confirm('你确定要删除' + name + '-' + value + '的这条信息吗', {
            btn: ['确定', '取消']
        }, function() {
            location.href = "/Z/Zzz/setDelete.php?f=" + v + "&t=" + n + "&p=" + path;
        }, function() {
            layer.msg('已取消操作!');
        });
    };

    // 临时标识恢复默认值
    window.setFlag = function(v, n) {
        var url = window.location.href;
        var path = encodeURIComponent(url);
        var value = window.atob(decodeURIComponent(v));
        var name = window.atob(decodeURIComponent(n));

        layer.confirm('你确定要' + name + '的临时标识全修改为' + value + '吗', {
            btn: ['确定', '取消']
        }, function() {
            location.href = "/Z/Zzz/setFlag.php?f=" + v + "&t=" + n + "&p=" + path;
        }, function() {
            layer.msg('已取消操作!');
        });
    };

    // 临时序号恢复默认值
    window.setSort = function(v, n) {
        var url = window.location.href;
        var path = encodeURIComponent(url);
        var value = window.atob(decodeURIComponent(v));
        var name = window.atob(decodeURIComponent(n));

        layer.confirm('你确定要' + name + '的临时序号全修改为' + value + '吗', {
            btn: ['确定', '取消']
        }, function() {
            location.href = "/Z/Zzz/setSort.php?f=" + v + "&t=" + n + "&p=" + path;
        }, function() {
            layer.msg('已取消操作!');
        });
    };

    // 自定义处理
    window.setTable = function(str) {
        var url = window.location.href;
        var path = encodeURIComponent(url);

        layer.confirm(decodeURIComponent(str) + '<br>你确定要修改吗', {
            btn: ['确定', '取消']
        }, function() {
            location.href = "/Z/Zzz/setTable.php?f=" + str + "&p=" + path;
        }, function() {
            layer.msg('已取消操作!');
        });
    };

    // 处理URL参数
    function setUrlParameter(selector, paramName, paramValue) {
        var $element = $(selector);
        if (!$element.length) return;

        var href = $element.attr('href') || '';
        var encodedValue = encodeURIComponent(paramValue);
        var escapedParamName = paramName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        var paramPattern = new RegExp(`(\\?|&)${escapedParamName}=([^&]*)`);

        if (paramPattern.test(href)) {
            href = href.replace(paramPattern, `$1${paramName}=${encodedValue}`);
        } else {
            var separator = href.includes('?') ? '&' : '?';
            href += `${separator}${paramName}=${encodedValue}`;
        }

        $element.attr('href', href);
    }

    // 防抖函数
    function debounce(func, delay) {
        let timer;
        return function() {
            const context = this;
            const args = arguments;
            clearTimeout(timer);
            timer = setTimeout(() => func.apply(context, args), delay);
        };
    }

    // 下拉菜单二级联动(添加防抖处理)
    function handleSelectChange(selectId, targetId, filterUrl) {
        form.on('select(' + selectId + ')', debounce(function(data) {
            const id = data.value;
            const tb = $(data.elem).data('tb');
            const mid = $(data.elem).data('mid');

            if (id === '0') return;

            const $target = $(targetId);
            $target.empty().append('<option value="">加载中...</option>');
            form.render('select');

            $.post(filterUrl, { id, tb, mid }, function(data) {
                $target.html(data);
                form.render('select');
            }).fail(function() {
                $target.html('<option value="">加载失败</option>');
                form.render('select');
            });
        }, 300));
    }

    // 页面初始化 - 执行入口
    $(function() {
        // 图片放大功能绑定
        $(".pimg").click(function() {
            var _this = $(this);
            imgShow("#outerdiv", "#innerdiv", "#bigimg", _this);
        });

        // 列表展开/收缩
        $('#opener').click(() => $('.icba-list-content').addClass('layui-show'));
        $('#toggle').click(() => $('.icba-list-content').toggleClass('layui-show'));

        // 多行文本域自动高度
        $.fn.autoHeight = function() {
            return this.each(function() {
                const resize = () => {
                    this.style.height = 'auto';
                    this.style.height = (this.scrollHeight) + 'px';
                };
                resize();
                $(this).on('keyup input', resize);
            });
        };
        $('textarea[autoHeight]').autoHeight();
        // 禁用拼写检查
        $('textarea').prop('spellcheck', false);

        // 数学公式渲染
        if (typeof renderMathInElement !== 'undefined') {
            const mathContainer = document.getElementById('katex');
            if (mathContainer) {
                renderMathInElement(mathContainer, {
                    delimiters: [
                        { left: '```math', right: '```', display: true },
                        { left: '`$', right: '$`', display: false }
                    ],
                    throwOnError: false
                });
            }
        }

        // 点击播放mp3音频的功能
        const audioCache = new Map();
        function playAudioSafely(audioPath) {
            let audio = audioCache.get(audioPath);
            if (!audio) {
                audio = new Audio(audioPath);
                audio.preload = 'auto';
                audioCache.set(audioPath, audio);
            }
            return audio.play().catch(error => {
                console.error('播放失败:', error);
                layer.msg('音频播放失败,请检查文件路径或浏览器设置', { icon: 2 });
                throw error;
            });
        }
        document.querySelectorAll('a[data-audio]').forEach(aTag => {
            aTag.addEventListener('click', function(e) {
                e.preventDefault();
                const audioPath = this.dataset.audio;
                playAudioSafely(audioPath);
            });
        });

        // 处理URL参数
        setUrlParameter('#save', 'url', window.location.href);
        setUrlParameter('#tell', 'url', window.location.href);
        setUrlParameter('#foot-tell', 'url', window.location.href);

        // 注册下拉菜单事件
        handleSelectChange('cbig_idFilter', '#cmin_id', '/Z/Zzz/filterCbig_id.php');
        handleSelectChange('c2big_idFilter', '#c2min_id', '/Z/Zzz/filterC2big_id.php');
        handleSelectChange('unitbig_idFilter', '#unitmin_id', '/Z/Zzz/filterUnitbig_id.php');
        handleSelectChange('unitbig2_idFilter', '#unitmin2_id', '/Z/Zzz/filterUnitbig_id.php');
        handleSelectChange('grp_idFilter', '#tt_id', '/Z/Zzz/filterGrp_id.php');
    });

});
posted @ 2025-08-07 18:57  onestopweb  阅读(10)  评论(0)    收藏  举报