-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
2056 lines (1771 loc) · 73.6 KB
/
script.js
File metadata and controls
2056 lines (1771 loc) · 73.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// 集成题库数据,不再依赖外部data.js文件
const quizData = {
math: [
{
question: "如果 2x + 3 = 7,那么 x 的值是多少?",
options: ["1", "2", "3", "4"],
answer: "B"
},
{
question: "一个圆的半径是5厘米,它的面积是多少平方厘米?(π取3.14)",
options: ["25π", "10π", "5π", "15π"],
answer: "A"
},
{
question: "如果 a + b = 10 且 a - b = 4,那么 a × b 的值是多少?",
options: ["21", "24", "18", "15"],
answer: "C"
},
{
question: "一个等边三角形的边长为6厘米,它的面积是多少平方厘米?",
options: ["9√3", "6√3", "12√3", "18√3"],
answer: "A"
},
{
question: "解方程:3(x - 2) = 2(x + 1)",
options: ["x = 8", "x = 7", "x = 6", "x = 5"],
answer: "D"
}
],
chinese: [
{
question: "下列词语中,加点字的读音完全正确的一项是()",
options: ["惬(qiè)意、诘(jié)问、窥(kuī)探", "贮(zhù)藏、稽(jī)查、绮(qǐ)丽", "憔(qiáo)悴、梗(gěng)概、诽(fěi)谤", "蹊(qī)跷、诧(chà)异、缄(jiān)默"],
answer: "D"
},
{
question: "下列各句中,没有语病的一句是()",
options: ["这部电影情节生动,演员表演到位,给观众留下了深刻的印象。", "随着互联网的发展,网络购物已经成为人们日常生活中不可或缺的一部分。", "我们要努力学习科学文化知识,为建设祖国的四个现代化而奋斗。", "这次比赛中,他发挥出色,一举夺得了冠军,创造了历史的最好成绩。"],
answer: "B"
},
{
question: "下列句子中,加点的成语使用恰当的一句是()",
options: ["这次考试,他考得很好,真是名不虚传。", "面对困难,我们要迎难而上,知难而退。", "他做事认真负责,处处都兢兢业业。", "这个问题很复杂,我们要抽丝剥茧地解决它。"],
answer: "C"
},
{
question: "下列各句中,没有歧义的一句是()",
options: ["我和他都去过北京。", "老师批评了学生的家长。", "这种药对感冒和发烧都有效。", "他送给我的礼物我很喜欢。"],
answer: "D"
},
{
question: "下列词语中,书写完全正确的一组是()",
options: ["博览群书、无懈可击、循序渐进", "博彩万象、无暇顾及、循循善诱", "博大精深、无微不至、循规蹈矩", "博古通今、无动于衷、循名责实"],
answer: "C"
}
],
english: [
{
question: "She _____ in this company for five years.",
options: ["works", "worked", "has worked", "had worked"],
answer: "C"
},
{
question: "If I _____ rich, I would buy a big house.",
options: ["am", "was", "were", "had been"],
answer: "C"
},
{
question: "The book _____ by John was very interesting.",
options: ["writes", "wrote", "written", "writing"],
answer: "C"
},
{
question: "You should _____ more attention to your health.",
options: ["pay", "take", "give", "have"],
answer: "A"
},
{
question: "I don't know _____ to solve this problem.",
options: ["how", "what", "when", "where"],
answer: "A"
}
]
};
// 排名数据
const rankingData = {
all: [
{ name: "张三", score: 98, rank: 1 },
{ name: "李明", score: 95, rank: 2 },
{ name: "王五", score: 92, rank: 3 },
{ name: "赵六", score: 90, rank: 4 },
{ name: "钱七", score: 88, rank: 5 },
{ name: "孙八", score: 85, rank: 6 },
{ name: "周九", score: 82, rank: 7 },
{ name: "吴十", score: 80, rank: 8 },
{ name: "郑十一", score: 78, rank: 9 },
{ name: "王十二", score: 75, rank: 10 }
],
math: [
{ name: "李明", score: 98, rank: 1 },
{ name: "张三", score: 95, rank: 2 },
{ name: "王五", score: 92, rank: 3 },
{ name: "赵六", score: 88, rank: 4 },
{ name: "钱七", score: 85, rank: 5 }
],
chinese: [
{ name: "张三", score: 96, rank: 1 },
{ name: "王五", score: 94, rank: 2 },
{ name: "李明", score: 92, rank: 3 },
{ name: "孙八", score: 90, rank: 4 },
{ name: "赵六", score: 88, rank: 5 }
],
english: [
{ name: "张三", score: 98, rank: 1 },
{ name: "钱七", score: 96, rank: 2 },
{ name: "李明", score: 94, rank: 3 },
{ name: "王五", score: 92, rank: 4 },
{ name: "吴十", score: 90, rank: 5 }
]
};
document.addEventListener('DOMContentLoaded', function() {
console.log('DOM加载完成');
// 确保quizData可用
window.quizData = quizData;
// 排名数据也设为全局
window.rankingData = rankingData;
// 定义用户成绩数据
const currentUserScores = {
math: 85,
chinese: 78,
english: 92,
science: 80,
history: 75
};
// 全局作用域定义,使其在所有函数中可用
window.currentUserScores = currentUserScores;
// 添加响应式样式
addResponsiveStyles();
// 获取所有导航链接
const navLinks = document.querySelectorAll('nav ul li a');
// 获取所有页面
const pages = document.querySelectorAll('.page');
// 为每个导航链接添加点击事件
navLinks.forEach(link => {
link.addEventListener('click', function(e) {
e.preventDefault();
// 移除所有导航链接的active类
navLinks.forEach(link => link.classList.remove('active'));
// 为当前点击的链接添加active类
this.classList.add('active');
// 获取要显示的页面id
const pageId = this.getAttribute('data-page') + '-page';
// 隐藏所有页面
pages.forEach(page => page.classList.remove('active'));
// 显示当前页面
document.getElementById(pageId).classList.add('active');
// 根据页面ID初始化不同功能
if (pageId === 'report-page') {
setTimeout(() => {
console.log('切换到学习报告页面,初始化所有报告功能');
initRadarChart();
identifyWeakAreas(); // 添加初始化薄弱项识别
initLearningTrends(); // 添加初始化学习趋势
}, 100);
} else if (pageId === 'home-page') {
initHomeTree();
}
});
});
// 初始化主页树
initHomeTree();
// 初始化答题模式
initQuizMode();
// 初始化排名榜
initRanking();
// 修改:检查当前页面,如果是学习报告页面,初始化所有报告功能
if (document.getElementById('report-page').classList.contains('active')) {
console.log('自动初始化学习报告');
initRadarChart();
identifyWeakAreas(); // 添加薄弱项识别
initLearningTrends(); // 添加学习趋势分析
}
// 获取答题设置元素
const quizSetup = document.getElementById('quiz-setup');
const quizSection = document.getElementById('quiz-section');
const startQuizBtn = document.getElementById('start-quiz-btn');
const restartBtn = document.getElementById('restart-btn');
// 设置按钮点击处理
const setupBtns = document.querySelectorAll('.setup-btn');
setupBtns.forEach(btn => {
btn.addEventListener('click', function() {
console.log('设置按钮被点击:', this.dataset);
// 移除同组中所有按钮的active类
const parentGroup = this.closest('.setup-group');
parentGroup.querySelectorAll('.setup-btn').forEach(b => {
b.classList.remove('active');
});
// 为当前按钮添加active类
this.classList.add('active');
});
});
// 开始答题按钮点击处理
startQuizBtn.addEventListener('click', function() {
console.log('开始答题按钮被点击');
// 获取用户选择的设置
const selectedSubject = document.querySelector('.setup-group:nth-child(1) .setup-btn.active').dataset.subject;
const selectedDifficulty = document.querySelector('.setup-group:nth-child(2) .setup-btn.active').dataset.difficulty;
const selectedMode = document.querySelector('.setup-group:nth-child(3) .setup-btn.active').dataset.mode;
console.log('选择的设置:', selectedSubject, selectedDifficulty, selectedMode);
// 保存用户选择
sessionStorage.setItem('quizSubject', selectedSubject);
sessionStorage.setItem('quizDifficulty', selectedDifficulty);
sessionStorage.setItem('quizMode', selectedMode);
// 根据选择设置答题界面
setupQuizInterface(selectedSubject, selectedDifficulty, selectedMode);
// 显示答题界面,隐藏设置界面
quizSetup.style.display = 'none';
quizSection.style.display = 'block';
// 启动答题
startQuiz(selectedSubject, selectedDifficulty, selectedMode);
});
// 重新开始按钮点击处理
restartBtn.addEventListener('click', function() {
console.log('重新开始按钮被点击');
try {
// 停止所有定时器
if (timerInterval) {
clearInterval(timerInterval);
}
if (opponentInterval) {
clearInterval(opponentInterval);
}
// 重置状态
currentQuestionIndex = 0;
score = 0;
correctAnswers = 0;
userAnswers = [];
// 隐藏结果和答题界面,显示设置界面
resultContainer.style.display = 'none';
quizContainer.style.display = 'none';
quizSection.style.display = 'none';
quizSetup.style.display = 'block';
console.log('已重置为初始状态');
} catch (error) {
console.error('重新开始时出错:', error);
alert('重新开始时出错,请刷新页面');
}
});
// 修改刷新雷达图按钮事件
const refreshRadarBtn = document.getElementById('refresh-radar');
if (refreshRadarBtn) {
refreshRadarBtn.addEventListener('click', function() {
console.log('点击刷新学习报告按钮');
initRadarChart();
identifyWeakAreas(); // 添加刷新薄弱项识别
initLearningTrends(); // 添加刷新学习趋势
});
}
});
// 初始化主页树功能
function initHomeTree() {
// 现有的HTML中已经有树的结构和样式,不需要通过JavaScript来创建
console.log('主页树已初始化');
// 获取学生各科成绩(从currentUserScores获取)
const englishScore = currentUserScores.english;
const chineseScore = currentUserScores.chinese;
const mathScore = currentUserScores.math;
// 更新成绩显示
document.querySelectorAll('.tree-info-item').forEach(item => {
const title = item.querySelector('.tree-info-title').textContent;
const valueElement = item.querySelector('.tree-info-value');
if (title === '英文成绩') {
valueElement.textContent = englishScore + '分';
} else if (title === '中文成绩') {
valueElement.textContent = chineseScore + '分';
} else if (title === '数学成绩') {
valueElement.textContent = mathScore + '分';
}
});
}
// 答题模式功能
function initQuizMode() {
console.log('初始化答题模式');
// 获取设置相关元素
const quizSetup = document.getElementById('quiz-setup');
const quizSection = document.getElementById('quiz-section');
const startQuizBtn = document.getElementById('start-quiz-btn');
const setupBtns = document.querySelectorAll('.setup-btn');
// 获取答题界面DOM元素
const subjectBtns = document.querySelectorAll('.subject-btn');
const questionElement = document.getElementById('question');
const option1Text = document.getElementById('option1-text');
const option2Text = document.getElementById('option2-text');
const option3Text = document.getElementById('option3-text');
const option4Text = document.getElementById('option4-text');
const currentQuestionElement = document.getElementById('current-question');
const totalQuestionsElement = document.getElementById('total-questions');
const nextBtn = document.getElementById('next-btn');
const submitBtn = document.getElementById('submit-btn');
const restartBtn = document.getElementById('restart-btn');
const quizContainer = document.querySelector('.quiz-container');
const resultContainer = document.querySelector('.result-container');
const timeElement = document.getElementById('time');
const resultTimeElement = document.getElementById('result-time');
const resultAccuracyElement = document.getElementById('result-accuracy');
const resultScoreElement = document.getElementById('result-score');
const radioButtons = document.querySelectorAll('.radio');
const optionElements = document.querySelectorAll('.option'); // 获取所有选项容器
const userProgressAvatar = document.getElementById('user-progress');
const opponentProgressAvatar = document.getElementById('opponent-progress');
const progressPointsContainers = document.querySelectorAll('.progress-points');
// 检查关键DOM元素是否存在
console.log('检查DOM元素:');
console.log('- questionElement:', !!questionElement);
console.log('- options:', !!option1Text, !!option2Text, !!option3Text, !!option4Text);
console.log('- radioButtons.length:', radioButtons.length);
console.log('- optionElements.length:', optionElements.length);
console.log('- nextBtn:', !!nextBtn);
console.log('- submitBtn:', !!submitBtn);
// 如果有关键元素不存在,输出错误并尝试修复
if (!questionElement || !option1Text || !option2Text || !option3Text || !option4Text ||
!nextBtn || !submitBtn || radioButtons.length === 0 || optionElements.length === 0) {
console.error('错误: 部分答题界面DOM元素未找到,可能导致功能故障');
// 这里可以添加恢复机制,例如刷新页面
}
// 当前状态变量
let currentSubject = 'math';
let currentQuestionIndex = 0;
let score = 0;
let correctAnswers = 0;
let startTime;
let timerInterval;
let userAnswers = [];
let opponentInterval;
let opponentCurrentQuestion = 0;
// 设置按钮点击处理
setupBtns.forEach(btn => {
btn.addEventListener('click', function() {
console.log('设置按钮被点击:', this.dataset);
// 移除同组中所有按钮的active类
const parentGroup = this.closest('.setup-group');
parentGroup.querySelectorAll('.setup-btn').forEach(b => {
b.classList.remove('active');
});
// 为当前按钮添加active类
this.classList.add('active');
});
});
// 开始答题按钮点击处理
startQuizBtn.addEventListener('click', function() {
console.log('开始答题按钮被点击');
// 获取用户选择的设置
const selectedSubject = document.querySelector('.setup-group:nth-child(1) .setup-btn.active').dataset.subject;
const selectedDifficulty = document.querySelector('.setup-group:nth-child(2) .setup-btn.active').dataset.difficulty;
const selectedMode = document.querySelector('.setup-group:nth-child(3) .setup-btn.active').dataset.mode;
console.log('选择的设置:', selectedSubject, selectedDifficulty, selectedMode);
// 保存用户选择
sessionStorage.setItem('quizSubject', selectedSubject);
sessionStorage.setItem('quizDifficulty', selectedDifficulty);
sessionStorage.setItem('quizMode', selectedMode);
// 根据选择设置答题界面
setupQuizInterface(selectedSubject, selectedDifficulty, selectedMode);
// 显示答题界面,隐藏设置界面
quizSetup.style.display = 'none';
quizSection.style.display = 'block';
// 启动答题
startQuiz(selectedSubject, selectedDifficulty, selectedMode);
});
// 设置答题界面函数
function setupQuizInterface(subject, difficulty, mode) {
console.log('设置答题界面:', subject, difficulty, mode);
// 更新显示的科目
const subjectBtns = document.querySelectorAll('.subject-btn');
subjectBtns.forEach(btn => {
if (btn.dataset.subject === subject) {
btn.classList.add('active');
} else {
btn.classList.remove('active');
}
});
// 如果是练习模式,隐藏计时器和对手进度
if (mode === 'practice') {
document.querySelector('.timer').style.display = 'none';
document.querySelector('.progress-track:nth-child(2)').style.display = 'none';
} else {
document.querySelector('.timer').style.display = 'block';
document.querySelector('.progress-track:nth-child(2)').style.display = 'flex';
}
// 设置题目数量和难度
// 这里可以根据不同难度调整题目数量
const totalQuestions = (difficulty.includes('grade1') || difficulty.includes('grade2')) ? 5 :
(difficulty.includes('grade3') || difficulty.includes('grade4')) ? 8 : 10;
document.getElementById('total-questions').textContent = totalQuestions;
}
// 开始答题函数
function startQuiz(subject, difficulty, mode) {
console.log('开始答题:', subject, difficulty, mode);
// 重置答题状态
document.getElementById('current-question').textContent = '1';
document.getElementById('question').textContent = '加载题目中...';
// 重置计时器
if (mode === 'speed') {
document.getElementById('time').textContent = '00:00';
startTimer();
}
// 更新当前科目 - 添加这一行来确保科目正确设置
currentSubject = subject;
// 初始化答题状态
resetQuiz();
// 直接加载题目
loadQuestion();
// 初始化进度条
initProgressBar();
}
// 重置答题状态函数
function resetQuiz() {
console.log('重置答题状态');
currentQuestionIndex = 0;
score = 0;
correctAnswers = 0;
userAnswers = [];
// 重置对手状态
opponentCurrentQuestion = 0;
// 清除对手定时器
if (opponentInterval) {
clearInterval(opponentInterval);
opponentInterval = null;
}
// 清除选项选中状态
radioButtons.forEach(radio => radio.checked = false);
optionElements.forEach(option => option.classList.remove('selected'));
// 不在此处重置进度头像位置,这将在initProgressBar中处理
// 因为我们需要精确计算正确的位置
// 重置界面状态
quizContainer.style.display = 'block';
resultContainer.style.display = 'none';
// 显示下一题按钮,隐藏提交按钮
nextBtn.style.display = 'block';
submitBtn.style.display = 'none';
}
// 开始计时器函数
function startTimer() {
console.log('开始计时');
// 记录开始时间
startTime = new Date();
// 清除之前的计时器
if (timerInterval) {
clearInterval(timerInterval);
}
// 设置计时器,每秒更新一次
timerInterval = setInterval(function() {
// 计算经过的时间(秒)
const elapsedTime = Math.floor((new Date() - startTime) / 1000);
const minutes = Math.floor(elapsedTime / 60);
const seconds = elapsedTime % 60;
// 更新时间显示
timeElement.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}, 1000);
}
// 声明全局变量,使其在其他函数中可用
window.currentSubject = currentSubject;
window.currentQuestionIndex = currentQuestionIndex;
window.resetQuiz = resetQuiz;
window.loadQuestion = loadQuestion;
window.initProgressBar = initProgressBar;
window.startTimer = startTimer;
window.showResult = showResult;
window.updateUserProgress = updateUserProgress;
window.startOpponentProgress = startOpponentProgress;
// 添加必要的DOM元素到全局作用域
window.questionElement = questionElement;
window.option1Text = option1Text;
window.option2Text = option2Text;
window.option3Text = option3Text;
window.option4Text = option4Text;
window.currentQuestionElement = currentQuestionElement;
window.nextBtn = nextBtn;
window.submitBtn = submitBtn;
window.radioButtons = radioButtons;
window.optionElements = optionElements;
window.quizContainer = quizContainer;
window.resultContainer = resultContainer;
window.timeElement = timeElement;
window.resultTimeElement = resultTimeElement;
window.resultAccuracyElement = resultAccuracyElement;
window.resultScoreElement = resultScoreElement;
window.userProgressAvatar = userProgressAvatar;
window.opponentProgressAvatar = opponentProgressAvatar;
window.progressPointsContainers = progressPointsContainers;
// 为选项添加点击事件
optionElements.forEach(optionElement => {
optionElement.addEventListener('click', function() {
console.log('选项被点击');
// 选中当前选项内的单选按钮
const radio = this.querySelector('input[type="radio"]');
if (radio) {
radio.checked = true;
// 移除所有选项的选中样式
optionElements.forEach(el => el.classList.remove('selected'));
// 为当前选项添加选中样式
this.classList.add('selected');
console.log('选择了选项:', radio.value);
} else {
console.error('选项中未找到单选按钮');
}
});
});
// 直接为所有选项元素添加点击事件,确保在任何情况下都能响应
document.addEventListener('click', function(event) {
// 检查点击的元素是否是选项或其子元素
const optionElement = event.target.closest('.option');
if (optionElement) {
const radio = optionElement.querySelector('input[type="radio"]');
if (radio) {
// 选中单选按钮
radio.checked = true;
// 移除所有选项的选中样式
document.querySelectorAll('.option').forEach(el => el.classList.remove('selected'));
// 为当前选项添加选中样式
optionElement.classList.add('selected');
console.log('通过委托选择了选项:', radio.value);
}
}
});
// 为单选按钮添加change事件
radioButtons.forEach(radio => {
radio.addEventListener('change', function() {
// 移除所有选项的选中样式
optionElements.forEach(el => el.classList.remove('selected'));
// 为当前选中单选按钮的父元素添加选中样式
this.closest('.option').classList.add('selected');
});
});
// 显示结果函数
function showResult() {
// 计算正确率
const accuracy = (correctAnswers / quizData[currentSubject].length) * 100;
// 更新结果显示
resultTimeElement.textContent = timeElement.textContent;
resultAccuracyElement.textContent = `${accuracy.toFixed(0)}%`;
resultScoreElement.textContent = score;
// 隐藏答题区域,显示结果区域
quizContainer.style.display = 'none';
resultContainer.style.display = 'block';
}
// 初始化题目总数
totalQuestionsElement.textContent = quizData[currentSubject].length;
// 初始化进度条
function initProgressBar() {
// 清空进度点容器
progressPointsContainers.forEach(container => {
container.innerHTML = '';
});
// 获取题目总数
const totalQuestions = quizData[currentSubject].length;
// 为每个进度条创建进度点
progressPointsContainers.forEach(container => {
for (let i = 0; i < totalQuestions; i++) {
const point = document.createElement('div');
point.className = 'progress-point';
container.appendChild(point);
}
});
// 重置对手当前题目
opponentCurrentQuestion = 0;
// 清除对手进度定时器
if (opponentInterval) {
clearInterval(opponentInterval);
}
// 等待DOM渲染完成后,设置初始位置
setTimeout(() => {
const progressBars = document.querySelectorAll('.progress-bar');
progressBars.forEach((progressBar, index) => {
const points = progressBar.querySelectorAll('.progress-point');
if (points.length > 0) {
// 获取第一个点和最后一个点的位置
const firstPoint = points[0];
const lastPoint = points[points.length - 1];
const firstPointRect = firstPoint.getBoundingClientRect();
const lastPointRect = lastPoint.getBoundingClientRect();
const barRect = progressBar.getBoundingClientRect();
// 计算点之间的间距
const totalProgressWidth = lastPointRect.left - firstPointRect.left;
const pointSpacing = points.length > 1 ? totalProgressWidth / (points.length - 1) : 0;
// 确定头像元素
const avatar = index === 0 ? userProgressAvatar : opponentProgressAvatar;
const avatarWidth = avatar.offsetWidth;
// 计算相对于进度条的位置
const baseLeftPosition = (firstPointRect.left - barRect.left);
// 设置初始位置
avatar.style.left = `${baseLeftPosition}px`;
} else {
// 如果没有点,使用默认内边距
const padding = 20;
// 获取头像
const avatar = index === 0 ? userProgressAvatar : opponentProgressAvatar;
// 设置初始位置为左侧内边距
avatar.style.left = `${padding}px`;
}
});
// 监听窗口大小变化,重新调整头像位置
window.addEventListener('resize', function() {
progressBars.forEach((progressBar, index) => {
const points = progressBar.querySelectorAll('.progress-point');
if (points.length > 0) {
// 重新计算进度条和进度点位置
const firstPoint = points[0];
const lastPoint = points[points.length - 1];
const updatedFirstPointRect = firstPoint.getBoundingClientRect();
const updatedLastPointRect = lastPoint.getBoundingClientRect();
const updatedBarRect = progressBar.getBoundingClientRect();
// 更新计算结果
const updatedTotalWidth = updatedLastPointRect.left - updatedFirstPointRect.left;
const updatedPointSpacing = points.length > 1 ? updatedTotalWidth / (points.length - 1) : 0;
const updatedBaseLeft = updatedFirstPointRect.left - updatedBarRect.left;
// 获取头像
const avatar = index === 0 ? userProgressAvatar : opponentProgressAvatar;
const currentQuestion = index === 0 ? currentQuestionIndex : opponentCurrentQuestion;
// 更新头像位置
avatar.style.left = `${updatedBaseLeft + (currentQuestion * updatedPointSpacing)}px`;
}
});
});
// 更新用户进度(当前题目的指示器)
updateUserProgress();
// 启动对手进度
startOpponentProgress();
}, 100); // 给DOM一点时间渲染
}
// 更新用户进度
function updateUserProgress() {
const totalQuestions = quizData[currentSubject].length;
const progressBar = document.querySelector('.progress-bar');
const progressWidth = progressBar.clientWidth;
// 获取进度点的位置
const progressPoints = progressBar.querySelectorAll('.progress-point');
// 如果有进度点,直接使用其位置
if (progressPoints.length > 0 && currentQuestionIndex < progressPoints.length) {
// 获取当前进度点的位置
const currentPoint = progressPoints[currentQuestionIndex];
const pointRect = currentPoint.getBoundingClientRect();
const barRect = progressBar.getBoundingClientRect();
// 计算相对位置,考虑到头像的尺寸
const avatarWidth = userProgressAvatar.offsetWidth;
const leftPos = (pointRect.left - barRect.left) - (avatarWidth / 2) + (currentPoint.offsetWidth / 2);
// 确保不超出边界
const minPos = 0;
const maxPos = progressWidth - avatarWidth;
const finalPos = Math.max(minPos, Math.min(maxPos, leftPos));
// 更新用户头像位置
userProgressAvatar.style.left = `${finalPos}px`;
} else {
// 如果没有进度点,使用均匀分布的方式
const padding = 20; // 两侧内边距
const availableWidth = progressWidth - (padding * 2);
const step = totalQuestions > 1 ? availableWidth / (totalQuestions - 1) : availableWidth;
// 计算新位置
const newPosition = currentQuestionIndex === 0 ?
padding :
padding + (step * currentQuestionIndex);
// 更新用户头像位置
userProgressAvatar.style.left = `${newPosition}px`;
}
}
// 启动对手进度随机前进
function startOpponentProgress() {
const totalQuestions = quizData[currentSubject].length;
const progressBar = document.querySelector('.progress-bar');
const progressWidth = progressBar.clientWidth;
const progressPoints = progressBar.querySelectorAll('.progress-point');
const avatarWidth = opponentProgressAvatar.offsetWidth;
// 清除之前可能存在的定时器
if (opponentInterval) {
clearInterval(opponentInterval);
}
// 添加一个初始延迟,确保不会在答题开始阶段就移动
// 使用一个更长的初始延迟,让用户有足够时间开始答题
const initialDelay = 8000 + Math.random() * 5000; // 8-13秒的初始延迟
// 先设置一个延时器,等待一段时间后再开始对手的移动
setTimeout(() => {
opponentInterval = setInterval(() => {
// 随机决定是否前进(70%的概率前进)
if (Math.random() < 0.7 && opponentCurrentQuestion < totalQuestions - 1) {
opponentCurrentQuestion++;
// 如果有进度点,直接使用其位置
if (progressPoints.length > 0 && opponentCurrentQuestion < progressPoints.length) {
const currentPoint = progressPoints[opponentCurrentQuestion];
const pointRect = currentPoint.getBoundingClientRect();
const barRect = progressBar.getBoundingClientRect();
// 计算相对位置
const leftPos = (pointRect.left - barRect.left) - (avatarWidth / 2) + (currentPoint.offsetWidth / 2);
// 确保不超出边界
const minPos = 0;
const maxPos = progressWidth - avatarWidth;
const finalPos = Math.max(minPos, Math.min(maxPos, leftPos));
// 更新对手头像位置
opponentProgressAvatar.style.left = `${finalPos}px`;
} else {
// 均匀分布方式
const padding = 20;
const availableWidth = progressWidth - (padding * 2);
const step = totalQuestions > 1 ? availableWidth / (totalQuestions - 1) : availableWidth;
// 计算新位置
const newPosition = opponentCurrentQuestion === 0 ?
padding :
padding + (step * opponentCurrentQuestion);
// 更新对手头像位置
opponentProgressAvatar.style.left = `${newPosition}px`;
}
// 如果对手完成所有题目,停止定时器
if (opponentCurrentQuestion >= totalQuestions - 1) {
clearInterval(opponentInterval);
}
}
}, 3000 + Math.random() * 4000); // 随机3-7秒前进一次
}, initialDelay);
}
// 为科目按钮添加点击事件
subjectBtns.forEach(btn => {
btn.addEventListener('click', function() {
// 移除所有按钮的active类
subjectBtns.forEach(btn => btn.classList.remove('active'));
// 为当前点击的按钮添加active类
this.classList.add('active');
// 更新当前科目
currentSubject = this.getAttribute('data-subject');
// 重置答题状态
resetQuiz();
// 加载第一题
loadQuestion();
// 初始化进度条
initProgressBar();
});
});
// 确保页面加载时已有题目显示
console.log('初始化第一道题目');
try {
// 确保quizData已加载
if (typeof quizData !== 'undefined' && quizData[currentSubject]) {
// 设置初始科目按钮为激活状态
subjectBtns.forEach(btn => {
if (btn.getAttribute('data-subject') === currentSubject) {
btn.classList.add('active');
}
});
// 加载第一道题目
resetQuiz();
loadQuestion();
// 初始化进度条
initProgressBar();
} else {
console.error('无法初始化第一道题目,quizData可能未加载');
questionElement.textContent = "数据加载错误,请刷新页面重试";
}
} catch (error) {
console.error('初始化第一道题目时出错:', error);
}
// 加载题目函数
function loadQuestion() {
try {
console.log('开始加载题目:', currentSubject, currentQuestionIndex);
// 确保quizData全局可用
if (typeof quizData === 'undefined' && typeof window.quizData !== 'undefined') {
quizData = window.quizData;
}
// 检查数据是否可用
if (!quizData || !quizData[currentSubject]) {
console.error('题目数据不可用:', currentSubject);
questionElement.textContent = "数据加载错误,请刷新页面重试";
return;
}
// 获取科目的所有题目
const questions = quizData[currentSubject];
// 检查题目索引是否有效
if (currentQuestionIndex >= questions.length) {
console.log('已完成所有题目');
showResult();
return;
}
// 获取当前题目
const currentQuestion = questions[currentQuestionIndex];
// 验证题目数据
if (!currentQuestion || !currentQuestion.question || !currentQuestion.options) {
console.error('题目数据无效:', currentQuestion);
questionElement.textContent = "题目加载失败,请刷新页面重试";
return;
}
// 更新界面
console.log('加载题目:', currentQuestion.question);
// 设置题目和选项
questionElement.textContent = currentQuestion.question;
option1Text.textContent = currentQuestion.options[0] || "选项A";
option2Text.textContent = currentQuestion.options[1] || "选项B";
option3Text.textContent = currentQuestion.options[2] || "选项C";
option4Text.textContent = currentQuestion.options[3] || "选项D";
// 更新题目计数
currentQuestionElement.textContent = currentQuestionIndex + 1;
totalQuestionsElement.textContent = questions.length;
// 清除选择状态
radioButtons.forEach(radio => radio.checked = false);
document.querySelectorAll('.option').forEach(opt => opt.classList.remove('selected'));
// 更新按钮状态
if (currentQuestionIndex === questions.length - 1) {
nextBtn.style.display = 'none';
submitBtn.style.display = 'block';
} else {
nextBtn.style.display = 'block';
submitBtn.style.display = 'none';
}
// 更新进度
updateUserProgress();
console.log('题目加载完成');
} catch (error) {
console.error('加载题目时出错:', error);
questionElement.textContent = "加载题目时出错,请刷新页面重试";
}
}
// 下一题按钮点击事件
nextBtn.addEventListener('click', function(event) {
event.preventDefault(); // 防止默认行为
console.log('下一题按钮被点击');
// 获取用户选择的答案
const selectedOption = document.querySelector('input[name="option"]:checked');
// 如果没有选择答案,提示用户
if (!selectedOption) {
alert('请选择一个答案!');
return;
}
try {
// 记录用户答案
userAnswers[currentQuestionIndex] = selectedOption.value;
// 检查答案是否正确
const currentQuestion = quizData[currentSubject][currentQuestionIndex];
if (selectedOption.value === currentQuestion.answer) {
score += 10;
correctAnswers++;
}
// 进入下一题
currentQuestionIndex++;
// 加载下一题
loadQuestion();
} catch (error) {
console.error('处理下一题时出错:', error);
alert('进入下一题时出错,请刷新页面重试');
}
});
// 提交按钮点击事件
submitBtn.addEventListener('click', function(event) {
event.preventDefault(); // 防止默认行为
console.log('提交按钮被点击');