吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 794|回复: 29
上一主题 下一主题
收起左侧

[学习记录] 小学四年级上册数学题批量生成_AI v1.0.0

  [复制链接]
跳转到指定楼层
楼主
xlz0303 发表于 2025-12-23 14:00 回帖奖励
本帖最后由 xlz0303 于 2025-12-23 14:03 编辑

用于生成小学四年级数学题生成的工具
支持选择题目类型:亿以内的加减、三位数乘两位数、除数是两位数的除法(整数)、乘除法估算法、四则运算(无括号)、四则运算(有括号)
支持配置题目数量(单类型上限200)
只能单独打印答案
(打印答案时可以直接导出为PDF,免的答案还得浪费纸张





[HTML] 纯文本查看 复制代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>四年级上册计算题生成器</title>
    <!-- 引入Tailwind CSS简化样式 -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 自定义配置 -->
    <script>
        // 确保Tailwind配置在加载完成后执行
        document.addEventListener('DOMContentLoaded', function() {
            tailwind.config = {
                theme: {
                    extend: {
                        colors: {
                            primary: '#4F46E5',
                            secondary: '#6366F1',
                            light: '#F3F4F6',
                        },
                        fontFamily: {
                            sans: ['Inter', 'system-ui', 'sans-serif'],
                        },
                    }
                }
            }
        });
    </script>
    <!-- 打印样式 -->
    <style type="text/css" media="print">
        @page {
            margin: 0;
            padding: 0;
        }
        .config-section, .action-buttons, header {
            display: none !important;
        }
        .question-section {
            display: block !important;
            margin: 0;
            padding: 0;
        }
        .question-section h2 {
            display: none !important;
        }
        .type-title {
            font-size: 18px !important;
            font-weight: bold !important;
            margin: 0.1rem 0 0.1rem 0 !important;
            padding: 0.1rem 0 !important;
            border-bottom: 2px solid #4F46E5 !important;
            color: #4F46E5 !important;
            page-break-after: avoid !important;
        }
        .question-item {
            margin-bottom: 0.1rem !important; /* 原1rem的2/3 */
            font-size: 16px;
            line-height: 1 !important; /* 行高压缩为原2/3左右 */
        }
    </style>
    <!-- 基础样式兼容 -->
    <style>
        /* 兼容低版本浏览器的基础样式 */
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        input[type="number"]::-webkit-outer-spin-button,
        input[type="number"]::-webkit-inner-spin-button {
            -webkit-appearance: none;
            margin: 0;
        }
        input[type="number"] {
            -moz-appearance: textfield;
            -webkit-appearance: none;
            appearance: none;
        }
        
        /* 打印预览样式 */
        .preview-mode .config-section, 
        .preview-mode .action-buttons, 
        .preview-mode header {
            display: none !important;
        }
        .preview-mode .question-section {
            display: block !important;
            margin: 0;
            padding: 0;
        }
        .preview-mode .question-section h2 {
            display: none !important;
        }
        .preview-mode .type-title {
            font-size: 18px !important;
            font-weight: bold !important;
            margin: 0.1rem 0 0.1rem 0 !important;
            padding: 0.1rem 0 !important;
            border-bottom: 2px solid #4F46E5 !important;
            color: #4F46E5 !important;
        }
        .preview-mode .question-item {
            margin-bottom: 0.1rem !important;
            font-size: 16px;
            line-height: 1 !important;
        }
        /* 预览模式下的退出按钮 */
        .exit-preview-btn {
            position: fixed;
            top: 20px;
            right: 20px;
            z-index: 1000;
            padding: 10px 20px;
            background-color: #EF4444;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-weight: bold;
            box-shadow: 0 2px 4px rgba(0,0,0,0.2);
        }
        .exit-preview-btn:hover {
            background-color: #DC2626;
        }
    </style>
</head>
<body class="bg-gray-50 min-h-screen">
    <div class="container mx-auto px-1 py-1 max-w-5xl"> <!-- 加宽容器适配4列 -->
        <!-- 标题 -->
        <header class="mb-8 text-center">
            <h1 class="text-[clamp(1.8rem,4vw,2.5rem)] font-bold text-primary mb-2">四年级上册计算题生成器</h1>
            <p class="text-gray-600">选择题目类型和数量,点击生成即可获取练习题</p>
        </header>

        <!-- 配置区域 -->
        <section class="config-section bg-white rounded-lg shadow-md p-6 mb-8">
            <h2 class="text-xl font-semibold text-gray-800 mb-4">题目配置</h2>
            
            <!-- 题目类型选项 -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-1 mb-6">
                <!-- 亿以内数的加减法 -->
                <div class="flex items-center space-x-3">
                    <input type="checkbox" id="type1" class="w-5 h-5 text-primary rounded border-gray-300 focus:ring-primary" checked>
                    <label for="type1" class="text-gray-700">亿以内数的加减法</label>
                    <div class="ml-auto flex items-center">
                        <label for="num1" class="text-gray-600 mr-2">数量:</label>
                        <input type="number" id="num1" min="1" max="200" value="50" class="w-16 px-2 py-1 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                    </div>
                </div>

                <!-- 三位数乘两位数 -->
                <div class="flex items-center space-x-3">
                    <input type="checkbox" id="type2" class="w-5 h-5 text-primary rounded border-gray-300 focus:ring-primary" checked>
                    <label for="type2" class="text-gray-700">三位数乘两位数</label>
                    <div class="ml-auto flex items-center">
                        <label for="num2" class="text-gray-600 mr-2">数量:</label>
                        <input type="number" id="num2" min="1" max="200" value="50" class="w-16 px-2 py-1 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                    </div>
                </div>

                <!-- 除数是两位数的除法(整除) -->
                <div class="flex items-center space-x-3">
                    <input type="checkbox" id="type3" class="w-5 h-5 text-primary rounded border-gray-300 focus:ring-primary" checked>
                    <label for="type3" class="text-gray-700">除数是两位数的除法(整除)</label>
                    <div class="ml-auto flex items-center">
                        <label for="num3" class="text-gray-600 mr-2">数量:</label>
                        <input type="number" id="num3" min="1" max="200" value="50" class="w-16 px-2 py-1 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                    </div>
                </div>

                <!-- 乘除法估算题 -->
                <div class="flex items-center space-x-3">
                    <input type="checkbox" id="type4" class="w-5 h-5 text-primary rounded border-gray-300 focus:ring-primary">
                    <label for="type4" class="text-gray-700">乘除法估算题</label>
                    <div class="ml-auto flex items-center">
                        <label for="num4" class="text-gray-600 mr-2">数量:</label>
                        <input type="number" id="num4" min="1" max="200" value="50" class="w-16 px-2 py-1 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                    </div>
                </div>

                <!-- 四则混合运算(无括号) -->
                <div class="flex items-center space-x-3">
                    <input type="checkbox" id="type5" class="w-5 h-5 text-primary rounded border-gray-300 focus:ring-primary">
                    <label for="type5" class="text-gray-700">四则混合运算(无括号)</label>
                    <div class="ml-auto flex items-center">
                        <label for="num5" class="text-gray-600 mr-2">数量:</label>
                        <input type="number" id="num5" min="1" max="200" value="50" class="w-16 px-2 py-1 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                    </div>
                </div>

                <!-- 四则混合运算(含括号) -->
                <div class="flex items-center space-x-3">
                    <input type="checkbox" id="type6" class="w-5 h-5 text-primary rounded border-gray-300 focus:ring-primary">
                    <label for="type6" class="text-gray-700">四则混合运算(含括号)</label>
                    <div class="ml-auto flex items-center">
                        <label for="num6" class="text-gray-600 mr-2">数量:</label>
                        <input type="number" id="num6" min="1" max="200" value="50" class="w-16 px-2 py-1 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                    </div>
                </div>
            </div>

            <!-- 列数选择(增加4列) -->
            <div class="flex items-center mb-4">
                <label for="columns" class="text-gray-700 mr-3">题目列数:</label>
                <select id="columns" class="px-3 py-1 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary">
                    <option value="1">1列</option>
                    <option value="2">2列</option>
                    <option value="3">3列</option>
                    <option value="4" selected>4列</option> <!-- 新增4列选项 -->
                </select>
            </div>
        </section>

        <!-- 操作按钮 -->
        <div class="action-buttons flex justify-center space-x-4 mb-8">
            <button id="generateBtn" class="px-6 py-2 bg-primary text-white rounded-md hover:bg-primary/90 transition-colors shadow-md hover:shadow-lg">
                生成题目
            </button>
            <button id="printBtn" class="px-6 py-2 bg-secondary text-white rounded-md hover:bg-secondary/90 transition-colors shadow-md hover:shadow-lg">
                打印题目
            </button>
            <button id="printAnswerBtn" class="px-6 py-2 bg-purple-600 text-white rounded-md hover:bg-purple-700 transition-colors shadow-md hover:shadow-lg">
                打印答案
            </button>
            <button id="previewBtn" class="px-6 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 transition-colors shadow-md hover:shadow-lg">
                打印预览
            </button>
            <button id="clearBtn" class="px-6 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 transition-colors shadow-md hover:shadow-lg">
                清空题目
            </button>
        </div>

        <!-- 题目展示区域 -->
        <section class="question-section bg-white rounded-lg shadow-md p-6 min-h-[300px]">
            <h2 class="text-xl font-semibold text-gray-800 mb-4">题目展示区</h2>
            <div id="questionContainer" class="grid grid-cols-1 md:grid-cols-2 gap-1">
                <p class="text-gray-500 italic">点击上方"生成题目"按钮开始生成...</p>
            </div>
        </section>
    </div>

    <script>
        // 工具函数:生成指定范围的随机数
        function getRandomNum(min, max) {
            // 增加参数校验,避免报错
            if (min >= max) {
                console.warn('最小值不能大于等于最大值,已自动修正');
                [min, max] = [max, min];
            }
            return Math.floor(Math.random() * (max - min + 1)) + min;
        }

        // 题目类型名称映射
        const questionTypeNames = {
            type1: '亿以内数的加减法',
            type2: '三位数乘两位数',
            type3: '除数是两位数的除法(整除)',
            type4: '乘除法估算题',
            type5: '四则混合运算(无括号)',
            type6: '四则混合运算(含括号)'
        };

        // 计算表达式结果的工具函数
        function calculateExpression(expr) {
            // 替换中文符号为数学符号
            expr = expr.replace(/×/g, '*').replace(/÷/g, '/');
            try {
                // 使用Function构造器安全计算(比eval更安全)
                return new Function('return ' + expr)();
            } catch (e) {
                console.error('计算表达式出错:', expr, e);
                return 0;
            }
        }

        // 估算函数
        function estimateExpression(expr) {
            if (expr.includes('×')) {
                // 乘法估算:四舍五入到最近的整十、整百数
                const [num1, num2] = expr.split('×').map(n => parseInt(n.trim()));
                const rounded1 = Math.round(num1 / 10) * 10;
                const rounded2 = Math.round(num2 / 10) * 10;
                return rounded1 * rounded2;
            } else if (expr.includes('÷')) {
                // 除法估算:将被除数和除数四舍五入后计算
                const [num1, num2] = expr.split('÷').map(n => parseInt(n.trim()));
                const rounded1 = Math.round(num1 / 10) * 10;
                const rounded2 = Math.round(num2 / 10) * 10;
                return Math.round(rounded1 / rounded2);
            }
            return 0;
        }

        // 各类型题目生成函数
        const questionGenerators = {
            // 1. 亿以内数的加减法
            type1: () => {
                let num1 = getRandomNum(10000, 99999999);
                let num2 = getRandomNum(10000, 99999999);
                const op = Math.random() > 0.5 ? '+' : '-';
                // 减法确保结果为正
                if (op === '-' && num1 < num2) [num1, num2] = [num2, num1];
                const question = `${num1} ${op} ${num2} = `;
                const expr = `${num1} ${op} ${num2}`;
                const answer = calculateExpression(expr);
                return { question, answer };
            },

            // 2. 三位数乘两位数
            type2: () => {
                const num1 = getRandomNum(100, 999);
                const num2 = getRandomNum(10, 99);
                const question = `${num1} × ${num2} = `;
                const answer = num1 * num2;
                return { question, answer };
            },

            // 3. 除数是两位数的除法(整除)
            type3: () => {
                const divisor = getRandomNum(10, 99); // 除数
                const quotient = getRandomNum(1, 99); // 商
                const dividend = divisor * quotient; // 被除数
                const question = `${dividend} ÷ ${divisor} = `;
                const answer = quotient;
                return { question, answer };
            },

            // 4. 乘除法估算题
            type4: () => {
                if (Math.random() > 0.5) {
                    // 乘法估算
                    const num1 = getRandomNum(10, 999);
                    const num2 = getRandomNum(10, 99);
                    const question = `${num1} × ${num2} ≈ `;
                    const expr = `${num1} × ${num2}`;
                    const answer = estimateExpression(expr);
                    return { question, answer };
                } else {
                    // 除法估算
                    const divisor = getRandomNum(10, 99);
                    const quotient = getRandomNum(1, 99);
                    const dividend = divisor * quotient + getRandomNum(0, divisor - 1);
                    const question = `${dividend} ÷ ${divisor} ≈ `;
                    const expr = `${dividend} ÷ ${divisor}`;
                    const answer = estimateExpression(expr);
                    return { question, answer };
                }
            },

            // 5. 四则混合运算(无括号)
            type5: () => {
                const ops = ['+', '-', '×', '÷'];
                // 确保除法能整除,增加循环退出机制避免死循环
                let num1, num2, num3, op1, op2;
                let loopCount = 0; // 防止死循环
                do {
                    loopCount++;
                    if (loopCount > 100) { // 超过100次循环则降级为加法
                        num1 = getRandomNum(1, 100);
                        num2 = getRandomNum(1, 100);
                        num3 = getRandomNum(1, 100);
                        op1 = '+';
                        op2 = '+';
                        break;
                    }
                    num1 = getRandomNum(1, 100);
                    num2 = getRandomNum(1, 100);
                    num3 = getRandomNum(1, 100);
                    op1 = ops[getRandomNum(0, 3)];
                    op2 = ops[getRandomNum(0, 3)];
                    
                    // 处理除法整除
                    let isValid = true;
                    if (op1 === '÷' && num1 % num2 !== 0) isValid = false;
                    if (op2 === '÷') {
                        if (op1 === '+' || op1 === '-') {
                            const temp = op1 === '+' ? num1 + num2 : num1 - num2;
                            if (temp <= 0 || temp % num3 !== 0) isValid = false;
                        } else {
                            if (num2 % num3 !== 0) isValid = false;
                        }
                    }
                    if (isValid) break;
                } while (true);

                const question = `${num1} ${op1} ${num2} ${op2} ${num3} = `;
                // 构造表达式字符串计算答案
                const expr = `${num1} ${op1} ${num2} ${op2} ${num3}`;
                const answer = calculateExpression(expr);
                return { question, answer };
            },

            // 6. 四则混合运算(含括号)
            type6: () => {
                const ops = ['+', '-', '×', '÷'];
                let num1, num2, num3, op1, op2, question, expr;
                let loopCount = 0; // 防止死循环
                do {
                    loopCount++;
                    if (loopCount > 100) { // 超过100次循环则降级为加法
                        num1 = getRandomNum(1, 100);
                        num2 = getRandomNum(1, 100);
                        num3 = getRandomNum(1, 100);
                        op1 = '+';
                        op2 = '+';
                        break;
                    }
                    num1 = getRandomNum(1, 100);
                    num2 = getRandomNum(1, 100);
                    num3 = getRandomNum(1, 100);
                    op1 = ops[getRandomNum(0, 3)];
                    op2 = ops[getRandomNum(0, 3)];

                    // 确保除法整除
                    let isValid = true;
                    if (op1 === '÷' && num1 % num2 !== 0) isValid = false;
                    if (op2 === '÷' && (op1 === '+' || op1 === '-')) {
                        const temp = op1 === '+' ? num1 + num2 : num1 - num2;
                        if (temp <= 0 || temp % num3 !== 0) isValid = false;
                    }
                    if (isValid) break;
                } while (true);

                // 随机选择括号位置
                if (Math.random() > 0.5) {
                    question = `(${num1} ${op1} ${num2}) ${op2} ${num3} = `;
                    expr = `(${num1} ${op1} ${num2}) ${op2} ${num3}`;
                } else {
                    // 确保后项除法整除
                    if (op2 === '÷' && num2 % num3 !== 0) {
                        num3 = getRandomNum(1, num2);
                        while (num2 % num3 !== 0 && loopCount < 100) {
                            num3 = getRandomNum(1, num2);
                            loopCount++;
                        }
                    }
                    question = `${num1} ${op1} (${num2} ${op2} ${num3}) = `;
                    expr = `${num1} ${op1} (${num2} ${op2} ${num3})`;
                }
                const answer = calculateExpression(expr);
                return { question, answer };
            }
        };

        // 全局变量:存储所有生成的题目和答案
        let generatedQuestions = [];

        // 生成题目主函数
        function generateQuestions() {
            try {
                const questionContainer = document.getElementById('questionContainer');
                if (!questionContainer) {
                    alert('未找到题目容器,请刷新页面重试');
                    return;
                }
                questionContainer.innerHTML = '';
                
                // 清空之前的题目和答案
                generatedQuestions = [];
                
                // 获取配置
                const columns = document.getElementById('columns')?.value || 2;
                
                // 遍历所有题目类型,按类型分组存储
                const types = ['type1', 'type2', 'type3', 'type4', 'type5', 'type6'];
                const questionsByType = {};
                let totalCount = 0;

                types.forEach(type => {
                    const checkbox = document.getElementById(type);
                    const numInput = document.getElementById(`num${type.slice(-1)}`);
                    
                    if (checkbox?.checked) {
                        const count = parseInt(numInput?.value) || 1;
                        // 限制最大数量为200,避免性能问题
                        const safeCount = Math.min(Math.max(count, 1), 200);
                        questionsByType[type] = [];
                        
                        // 生成对应数量的题目
                        for (let i = 0; i < safeCount; i++) {
                            try {
                                const result = questionGenerators[type]();
                                questionsByType[type].push(result);
                                // 将题目和答案添加到全局数组
                                generatedQuestions.push({
                                    type: type,
                                    index: totalCount + 1,
                                    question: result.question,
                                    answer: result.answer
                                });
                                totalCount++;
                            } catch (e) {
                                console.error(`生成${type}题目失败:`, e);
                                const errorQuestion = { question: `题目生成失败(${type})`, answer: '' };
                                questionsByType[type].push(errorQuestion);
                                generatedQuestions.push({
                                    type: type,
                                    index: totalCount + 1,
                                    question: errorQuestion.question,
                                    answer: errorQuestion.answer
                                });
                                totalCount++;
                            }
                        }
                    }
                });

                // 渲染题目
                if (totalCount === 0) {
                    questionContainer.innerHTML = '<p class="text-red-500">请至少选择一种题目类型!</p>';
                    return;
                }

                // 按类型渲染题目
                let globalIndex = 1;
                Object.keys(questionsByType).forEach(type => {
                    const questions = questionsByType[type];
                    if (questions.length === 0) return;

                    // 创建类型标题
                    const typeTitle = document.createElement('div');
                    typeTitle.className = 'type-title w-full col-span-full text-xl font-bold text-primary mb-4 pt-6 border-t border-gray-200 print:border-t-0';
                    typeTitle.innerHTML = `${questionTypeNames[type]}`;
                    questionContainer.appendChild(typeTitle);

                    // 创建类型题目容器
                    const typeContainer = document.createElement('div');
                    typeContainer.className = `grid grid-cols-${columns} gap-1 w-full col-span-full`;
                    
                    // 渲染当前类型的所有题目
                    questions.forEach(q => {
                        const questionItem = document.createElement('div');
                        questionItem.className = 'question-item p-2 border-b border-gray-100';
                        questionItem.innerHTML = `<span class="font-medium text-gray-800">${globalIndex}.</span> ${q.question}`;
                        typeContainer.appendChild(questionItem);
                        globalIndex++;
                    });
                    
                    questionContainer.appendChild(typeContainer);
                });
            } catch (e) {
                console.error('生成题目失败:', e);
                alert('生成题目时出错,请查看控制台或刷新页面重试');
            }
        }

        // 清空题目
        function clearQuestions() {
            const questionContainer = document.getElementById('questionContainer');
            if (questionContainer) {
                questionContainer.innerHTML = '<p class="text-gray-500 italic">点击上方"生成题目"按钮开始生成...</p>';
            }
            // 清空答案数组
            generatedQuestions = [];
        }
        
        // 退出预览模式
        function exitPreview() {
            // 移除预览模式类
            document.body.classList.remove('preview-mode');
            
            // 移除退出预览按钮
            const exitBtn = document.getElementById('exitPreviewBtn');
            if (exitBtn) {
                exitBtn.remove();
            }
        }

        // 打印答案函数
        function printAnswers() {
            // 检查是否有生成的答案
            if (generatedQuestions.length === 0) {
                alert('请先生成题目再打印答案!');
                return;
            }

            // 获取列数配置
            const columns = document.getElementById('columns')?.value || 2;
            
            // 创建临时打印页面
            const printWindow = window.open('', '_blank');
            if (!printWindow) {
                alert('无法打开打印窗口,请检查浏览器弹出窗口设置!');
                return;
            }

            // 构建打印内容
            printWindow.document.write(`
                <!DOCTYPE html>
                <html lang="zh-CN">
                <head>
                    <meta charset="UTF-8">
                    <meta name="viewport" content="width=device-width, initial-scale=1.0">
                    <title>答案 - 四年级上册计算题</title>
                    <script src="https://cdn.tailwindcss.com"><\/script>
                    <style>
                        body {
                            font-family: Inter, system-ui, sans-serif;
                            margin: 20px;
                        }
                        .type-title {
                            font-size: 20px;
                            font-weight: bold;
                            color: #4F46E5;
                            margin: 20px 0 10px 0;
                            padding-bottom: 5px;
                            border-bottom: 2px solid #4F46E5;
                        }
                        .answer-container {
                            display: grid;
                            grid-template-columns: repeat(${columns}, 1fr);
                            gap: 10px;
                            margin-bottom: 20px;
                        }
                        .answer-item {
                            font-size: 16px;
                            padding: 8px;
                            border-bottom: 1px solid #e5e7eb;
                        }
                    </style>
                </head>
                <body>
                    <h1 style="text-align: center; font-size: 24px; font-weight: bold; margin-bottom: 30px; color: #4F46E5;">四年级上册计算题答案</h1>
            `);

            // 按类型分组答案
            const answersByType = {};
            generatedQuestions.forEach(item => {
                if (!answersByType[item.type]) {
                    answersByType[item.type] = [];
                }
                answersByType[item.type].push(item);
            });

            // 渲染答案
            Object.keys(answersByType).forEach(type => {
                const items = answersByType[type];
                printWindow.document.write(`
                    <div class="type-title">${questionTypeNames[type]} - 答案</div>
                    <div class="answer-container">
                `);
                
                items.forEach(item => {
                    printWindow.document.write(`
                        <div class="answer-item">
                            <span style="font-weight: bold;">${item.index}.</span> ${item.answer}
                        </div>
                    `);
                });
                
                printWindow.document.write('</div>');
            });

            printWindow.document.write('</body></html>');
            printWindow.document.close();

            // 等待文档加载完成后打印
            printWindow.onload = function() {
                printWindow.print();
                
                // 处理打印完成或取消的情况
                // 方法1:监听onafterprint事件(适用于实际打印完成的情况)
                printWindow.onafterprint = function() {
                    printWindow.close();
                };
                
                // 方法2:如果用户取消打印,当主窗口重新获得焦点时关闭打印窗口
                window.onfocus = function() {
                    setTimeout(function() {
                        if (printWindow && !printWindow.closed) {
                            printWindow.close();
                        }
                        // 恢复主窗口的onfocus事件
                        window.onfocus = null;
                    }, 100);
                };
            };
        }

        // 页面加载完成后绑定事件
        document.addEventListener('DOMContentLoaded', () => {
            // 绑定生成按钮
            const generateBtn = document.getElementById('generateBtn');
            if (generateBtn) {
                generateBtn.addEventListener('click', generateQuestions);
            }
            
            // 绑定打印按钮
            const printBtn = document.getElementById('printBtn');
            if (printBtn) {
                printBtn.addEventListener('click', () => {
                    // 打印前检查是否有题目
                    const questionContainer = document.getElementById('questionContainer');
                    if (questionContainer?.innerText.includes('点击上方')) {
                        alert('请先生成题目再打印!');
                        return;
                    }
                    window.print();
                });
            }
            
            // 绑定打印预览按钮
            const previewBtn = document.getElementById('previewBtn');
            if (previewBtn) {
                previewBtn.addEventListener('click', () => {
                    // 预览前检查是否有题目
                    const questionContainer = document.getElementById('questionContainer');
                    if (questionContainer?.innerText.includes('点击上方')) {
                        alert('请先生成题目再预览!');
                        return;
                    }
                    
                    // 切换到预览模式
                    document.body.classList.add('preview-mode');
                    
                    // 添加退出预览按钮
                    const exitBtn = document.createElement('button');
                    exitBtn.id = 'exitPreviewBtn';
                    exitBtn.className = 'exit-preview-btn';
                    exitBtn.innerText = '退出预览';
                    document.body.appendChild(exitBtn);
                    
                    // 绑定退出预览事件
                    exitBtn.addEventListener('click', exitPreview);
                });
            }
            
            // 绑定清空按钮
            const clearBtn = document.getElementById('clearBtn');
            if (clearBtn) {
                clearBtn.addEventListener('click', clearQuestions);
            }

            // 绑定打印答案按钮
            const printAnswerBtn = document.getElementById('printAnswerBtn');
            if (printAnswerBtn) {
                printAnswerBtn.addEventListener('click', printAnswers);
            }

            // 数量输入框限制只能输入数字且最小值为1(上限改为200)
            const numInputs = document.querySelectorAll('input[type="number"]');
            numInputs.forEach(input => {
                input.addEventListener('input', () => {
                    if (!input.value) input.value = 1;
                    const val = parseInt(input.value);
                    if (val < 1) input.value = 1;
                    if (val > 200) input.value = 200; // 上限改为200
                });
                // 兼容失去焦点事件
                input.addEventListener('blur', () => {
                    if (!input.value) input.value = 1;
                });
            });

            // 列数选择变更时更新布局(支持4列)
            const columnsSelect = document.getElementById('columns');
            if (columnsSelect) {
                columnsSelect.addEventListener('change', function() {
                    const container = document.getElementById('questionContainer');
                    if (container) {
                        container.className = `grid grid-cols-${this.value} gap-1`;
                    }
                });
            }
        });
    </script>
</body>
</html>


蓝奏云地址:https://xlz0303.lanzoum.com/i2eDQ3eaee5g

免费评分

参与人数 1热心值 +1 收起 理由
mengfang1 + 1 非常感谢

查看全部评分

本帖被以下淘专辑推荐:

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

沙发
 楼主| xlz0303 发表于 2025-12-23 14:05 |楼主
豆包AI+手动修改了一部分,有啥问题可以在评论区中评论
3#
牛人王老五 发表于 2025-12-23 16:29
挺好的, 我建议可以把功能扩大一些, 不必限制在小学四年级.
比如添加以下功能:
1. 加减乘除自定义
2. 计算的项数自定义
3. 小数位数以及整数长度的选择, 限制答案为整数, 是否去除负数
4. 题目取值范围自定义, 答案范围自定义
5. 增加填空题和竖式的选择
6. 增加小数, 百分数, 比例, 单位换算等不同数据类型的选择
7. 考虑可以生成word/TXT等格式报告, 方便打印
4#
lmyx2008 发表于 2025-12-23 18:43
5#
 楼主| xlz0303 发表于 2025-12-23 18:51 |楼主
牛人王老五 发表于 2025-12-23 16:29
挺好的, 我建议可以把功能扩大一些, 不必限制在小学四年级.
比如添加以下功能:
1. 加减乘除自定义

嗯嗯,后续有这个想法,打算自己实现一下小学数学从1-6年级的随机生成,到时候直接按照年级+单元直接生成题目,目前这个版本只是用来给家里小孩刷题的
6#
 楼主| xlz0303 发表于 2025-12-23 18:54 |楼主

是啊,家里的小孩单元考30分,所以才想着写个自动生成题目,好好加练
7#
嘿嘿嘿001 发表于 2025-12-23 21:01
牛逼啊,这小学生的噩梦
8#
小蚂蚁哈哈乐 发表于 2025-12-23 22:02
大佬能不能增加个五年级的
9#
ShellKnight 发表于 2025-12-23 22:52
大佬,可以生成低年级的么
10#
我要开始装逼了 发表于 2025-12-23 23:38
关键马上下学期了
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - 52pojie.cn ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2025-12-25 13:49

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表