首页 > 其他分享 >划词答题——nsyh 0.02

划词答题——nsyh 0.02

时间:2024-02-28 20:02:12浏览次数:14  
标签:function gv const 0.02 changetranslatebox 划词 nsyh document display

// ==UserScript==
// @name         划词答题——nsyh
// @namespace    nsyh
// @version      0.0.2
// @description  选中题目一会放开自动答题,需要自己上传EXCEL的XSLX格式的题库,表头为ID、PW;ID列放题目,PW列放答案;新增点击喇叭自动答题

// @author       Jubai_P
// @match        *://*.sdnsyh.21tb.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=21tb.com
// @grant        GM_xmlhttpRequest
// @grant        GM_addStyle
// @require      https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js
// @require      https://cdn.bootcdn.net/ajax/libs/xlsx-populate/1.21.0/xlsx-populate.min.js
// @require      https://cdn.bootcdn.net/ajax/libs/xlsx/0.18.5/xlsx.full.min.js
// @license             MIT
// ==/UserScript==



(function() {

    'use strict';

    var gv = {toLanguage:'zh-CN',isAutoCopy:true};

    if (/zh/i.test(navigator.language)) gv.toLanguage='zh-CN';
    else if (/ja/i.test(navigator.language)) gv.toLanguage='ja';
    else if (/en/i.test(navigator.language)) gv.toLanguage='en';

    function init() {
        $(document).ready(function() {
            var ctrlDown = false,
                altDown = false,
                ctrlKey = 17,
                cmdKey = 91,
                altKey = 18,
                vKey = 86,
                cKey = 67;

            $(document).keydown(function(e) {
                if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = true;
                if (e.keyCode == altKey) altDown = true;
            }).keyup(function(e) {
                if (e.keyCode == ctrlKey || e.keyCode == cmdKey) ctrlDown = false;
                if (e.keyCode == altKey) altDown = false;
            });

            $(".no-copy-paste").keydown(function(e) {
                if (ctrlDown && (e.keyCode == vKey || e.keyCode == cKey)) return false;
            });

            $(document).keydown(function(e) {
                if (ctrlDown && (e.keyCode == cKey)) {gv.isAutoCopy = false};
                if (altDown && (e.keyCode == cKey)){gv.isAutoCopy = true};
                //if (ctrlDown && (e.keyCode == vKey)) console.log("Document catch Ctrl+V");
            });
        });

        document.addEventListener('mousedown', function(e){
            if (!$('#changetranslatebox') || $('#changetranslatebox').length == 0) {
               //触发显示

                createDisplay();
                $('#changetranslatebox input').on('click', function(e){
                     //设置触发文件上传
                      $("input[id='test_button']").change(function(){
                     importXlsx(this.files[0]);
                                              });

                    gv.toLanguage = e.target.getAttribute('name')
                    $('.translatedropdown').css('display', '');
                    _translate();


                    //设置名字为空
                   // setTimeout(function() { $('.translatetext').empty();}, 500);
                });
            }
            if ($('#changetranslatebox').css('display') == 'block' && !checkClick(e)) {
                $('#changetranslatebox').css('display', '');
                $('.translatedropdown').css('display', '');
                $('.translatetext').empty();
                $('.translateexplain').empty();
            }
            clearTimeout(gv.timer);
            gv.holdTime = false;
            gv.timer = setTimeout(function() { gv.holdTime = true; }, 500);
            if (e.target.className == 'translateplaysound') {
                $('.translateplaysound').addClass('translateplaysoundClick');
                playSound();
            } else if (e.target.className == 'translatelanguageset') {
                $('.translatedropdown').css('display', 'block');
            }
        }, true);

        document.addEventListener('mouseup', function(e){
             if (gv.holdTime == true && window.getSelection().toString()) {
                e.preventDefault()
                e.stopPropagation();
                gv.holdTime = false;
                showBox(e.clientX, e.clientY);
                gv.selectText = window.getSelection().toString();
                 //输出选择文字
                  console.log("选择问题:",gv.selectText)
                gv.encodeText = encodeURIComponent(gv.selectText);
                _translate();
            }
            if ($('.translateplaysoundClick') && $('.translateplaysoundClick').length > 0) {
                $('.translateplaysound').removeClass('translateplaysoundClick');
            }

              //判断文件是否上传
                    if (BOOM  == null || BOOM ==undefined ||BOOM ==''){
                    $('.translatetext').text( '文件未上传');
                    }
                    else{
                     $('.translatetext').text( '文件已上传');
                    }
            clearTimeout(gv.timer);
        }, true);
    }

    function createDisplay() {
        setStyle(['#changetranslatebox * {margin:0;padding:0;box-sizing:border-box;}','#changetranslatebox {min-height:24px;min-width:100px;max-width:360px;font:normal 12px/24px Helvetica, Tahoma, Arial, sans-serif;text-align: left;position: absolute;z-index: 2147483647;top: 22px;left: -35px;background: #fff;border: 1px solid #dcdcdc;-webkit-transition: opacity .218s;transition: opacity .218s;box-shadow: 0 1px 4px rgba(0,0,0,.2);padding: 5px 0;display: none;font-size: 12px;line-height: 20px;border-radius:3px;}','#changetranslatebox .translatecontentbox {margin:0 8px;color:#333;}','#changetranslatebox .translatecontentbox .translatetextbox{line-height:16px;border-bottom: 1px solid #ccc;padding: 2px 18px 9px 0;height: 25px;}','#changetranslatebox .translatecontentbox .translatetextbox div{vertical-align: middle;margin-right: 4px;color:#333;font-weight: normal;font-size:12px;}','#changetranslatebox .translatecontentbox .translatetextbox .translatetext{display: inline-block;font-size:14px;font-weight: bold;color:#333;}','#changetranslatebox .translatecontentbox .translatetextbox .translateplaysound {margin-left: 1px;cursor:pointer;display: inline-block;vertical-align: middle;width: 14px;height: 11px;overflow: hidden;background: url("data:image/gif;base64,R0lGODlhDgAZAIAAABy3/f///yH5BAAAAAAALAAAAAAOABkAAAI1jA+nC7ncXmg0RlTvndnt7jlcxkmjqWzotLbui4qxqBpUmoDl2Nk5GOKRSsCfDyer7ZYMSQEAOw==") no-repeat;text-decoration: none;}','#changetranslatebox .translatecontentbox .translatetextbox .translateplaysound.translateplaysoundClick {background-position:0 -14px;}','#changetranslatebox .translatecontentbox .translateexplain{padding: 2px 0 0 0;font-weight: normal;font-size:12px;}','#changetranslatebox .translatetiparrow {width: 0;height: 0;font-size: 0;line-height: 0;display: block;position: absolute;top: -16px;left: 10px;}','#changetranslatebox .translatetiparrow em, #changetranslatebox .translatetiparrow ins {width: 0;height: 0;font-size: 0;line-height: 0;display: block;position: absolute;border: 8px solid transparent;border-style: dashed dashed solid;}','#changetranslatebox .translatetiparrow em {border-bottom-color: #d8d8d8;font-style: normal;color: #c00;}','#changetranslatebox .translatetiparrow ins {border-bottom-color: #fff;top: 2px;text-decoration: underline;background:none !important}','#changetranslatebox .translatelanguageset {position:absolute;top:9px;right:10px;cursor: pointer;width: 14px;height: 14px;background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAA4AAAAOCAMAAAAolt3jAAAAdVBMVEUAAAAwi/+Zxv9urv9oq/9pq/9Elv81jf89kv8wiv8+kv8wiv8xi/8wi/9/t/9+t/9co/9Zof9Hl/9Gl/9ClP9Bk/85j//k8f/Z6v+Fu//x+P/e7f/b6//G3/+/2/+w0/+q0P+52P+42P+Lvv+IvP9wr/9vr/864/KKAAAAF3RSTlMAR/7s7OK7l5VuTyMTC/z7y8ihnYSAQ/Vmp/0AAAB9SURBVAjXVY9HDsQwDAPpVKf32E7v/3/iGtJhk7kNIIgkLH0QA3EgQHTX7AnhzWdLKo9hMWYZdkmaFFpZdJ6QRo7afH9TTmSlqcy4hmkarqMpazxq0m4GZK6e1I37rQ/q8n9cNZ9XHJRzUMFBcucaB9doTy55dSAET+gB/ABPjgqB+Q/YPgAAAABJRU5ErkJggg==") no-repeat;text-decoration: none;}','#changetranslatebox .translatelanguageset .translatedropdown {margin:0;padding:0;display:none;top:13px;right:-60px;position: absolute;background-color: #ffffff;width: 68px;overflow: auto;z-index: 1;border: 1px solid rgba(0,0,0,.2);box-shadow: 0 2px 4px rgba(0,0,0,.2);}','#changetranslatebox .translatelanguageset .translatedropdown li {list-style-type:none; color: black;padding: 6px 8px;margin:0px;text-decoration: none;display: block;text-align:center;}','#changetranslatebox .translatelanguageset .translatedropdown li:hover { background-color: #f1f1f1;}']);
        $('<div id="changetranslatebox"><div class="translatecontentbox"><div class="translatetextbox"><div class="translatetext"></div><div class="translateplaysound"></div></div><div class="translateexplainbox"><div class="translateexplain"></div><div class="translateplaysound"></div></div></div><div class="translatetiparrow"><em></em><ins></ins></div><div class="translatelanguageset"><ul class="translatedropdown"><li name="zh-CN">上传EXCEL</li><input id="test_button" type="file" value="导入表格"></input></ul></div></div>').appendTo($(document.body));
    }







    function showBox(mouseX, mouseY) {
        var changetranslatebox = document.getElementById('changetranslatebox');
        var selectedRect = window.getSelection().getRangeAt(0).getBoundingClientRect();
        var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
        if (selectedRect.width) {if (getComputedStyle(document.body).position != 'static') {changetranslatebox.style.top = selectedRect.bottom - document.body.getBoundingClientRect().top + 8 + 'px';} else {changetranslatebox.style.top = selectedRect.bottom + scrollTop + 8 + 'px';}changetranslatebox.style.left = selectedRect.left + selectedRect.width / 2 - 18 + 'px';} else {changetranslatebox.style.top = mouseY - document.body.getBoundingClientRect().y + selectedRect.height + 8 + 'px';changetranslatebox.style.left = mouseX + selectedRect.width / 2 - 18 + 'px';}
        changetranslatebox.style.display = 'block';
    }

    function setStyle(css){
        if(typeof(css) == "string") GM_addStyle(css);
        else for(var i=0;i<css.length;i++){GM_addStyle(css[i]) }
    }

    //中文表达式
    var pattern = new RegExp("[\u4e00-\u9fa5]+");
    function _translate() {
        //googleTrans.Execute(pattern.test(gv.selectText)?gv.encodeText:gv.selectText, 'auto', gv.toLanguage, (ret)=>{
       //匹配方案1
        //playSound()
        //方案2

        search(gv.selectText)

        //})
    }
    //解析结果
    function parseResult(result) {
        var explains = '';
        var obj = JSON.stringify(result);

        try{
            if( typeof(obj) == 'string') gv.explains = obj;
               else

                   gv.explains = obj.join('\n');
            $('.translateexplain').text(gv.explains);
            if (navigator.clipboard && gv.isAutoCopy) {
                navigator.clipboard.writeText(gv.selectText+'\n'+gv.explains);
            }
        }catch(e){
            $('.translateexplain').text('翻译失败');
        }
    }

    function checkClick(e) {
        var path = e.path || e.composedPath();
        if (path.indexOf($('#changetranslatebox').get(0)) > -1) return true;
        else return false;
    }

        //设置题库BOOM
    let BOOM = []

    //上传数据
    function importXlsx(file) {
        console.log("触发读取");
            var reader = new FileReader();
            reader.onload = function(event) {
                const datas = event.target.result;
                // console.log("触发读取");
                const workbook = XLSX.read(datas, { type: "binary" });
                const sheet = workbook.Sheets[workbook.SheetNames[0]]
                const json = XLSX.utils.sheet_to_json(sheet);
                console.log(json);
                //题库升级
                BOOM = json;

            }
            reader.readAsBinaryString(file);
        }


                //播放

    function playSound(arraybuffer) {
   answerAllQuestion()
        };

// 自动答题函数 一键答题
function answerAllQuestions() {
    // Iterate through each question
    BOOM.forEach((question) => {
        const questionText = question.ID;
        const answer = question.PW;

        // Check if it's a single choice question
        const singleChoiceQuestions = document.querySelectorAll('.question-panel-middle.SINGLE');
        singleChoiceQuestions.forEach((singleQuestionElement) => {
            const questionElement = singleQuestionElement.querySelector('.name');
            if (questionElement.textContent.includes(questionText)) {
                const radioOptions = singleQuestionElement.querySelectorAll('input[type="radio"]');
                radioOptions.forEach((option) => {
                    if (option.nextElementSibling.innerText.includes(answer)) {
                        option.click();
                        console.log(`Question: ${questionText}\nAnswer: ${answer}`);
                    }
                });
            }
        });

        // Check if it's a multiple choice question
        const multipleChoiceQuestions = document.querySelectorAll('.question-panel-middle.MULTIPLE');
        multipleChoiceQuestions.forEach((multipleQuestionElement) => {
            const questionElement = multipleQuestionElement.querySelector('.name');
            if (questionElement.textContent.includes(questionText)) {
                const checkboxOptions = multipleQuestionElement.querySelectorAll('input[type="checkbox"]');
                checkboxOptions.forEach((option) => {
                    if (answer.includes(option.nextElementSibling.innerText.trim().charAt(0))) {
                        option.click();
                    }
                });
                console.log(`Question: ${questionText}\nAnswer: ${answer.split('').join(', ')}`);
            }
        });

        // Check if it's a judgment question
        const judgmentQuestions = document.querySelectorAll('.question-panel-middle.JUDGMENT');
        judgmentQuestions.forEach((judgmentElement) => {
            const questionElement = judgmentElement.querySelector('.name');
            if (questionElement.textContent.includes(questionText)) {
                const trueOption = judgmentElement.querySelector('input[value="true"]');
                const falseOption = judgmentElement.querySelector('input[value="false"]');

                if (answer === "A") {
                    trueOption.click();
                    console.log(`Question: ${questionText}\nAnswer: True`);
                } else if (answer === "B") {
                    falseOption.click();
                    console.log(`Question: ${questionText}\nAnswer: False`);
                }
            }
        });
    });
}






    //匹配算法2


    function search(keyword) {

	const patterns = new RegExp(keyword, 'i'); // 不区分大小写
	let item2= BOOM.filter(item => {

        return patterns.test(item.ID) || patterns.test(item.PW) ;

					});
        //输出的是字典
           console.log(item2)
        parseResult(item2)
				}







    init();

})();

标签:function,gv,const,0.02,changetranslatebox,划词,nsyh,document,display
From: https://www.cnblogs.com/jubai/p/18041630

相关文章

  • 一款简洁高效的输入、截图、划词翻译软件
    大家好,我是Java陈序员。英语是我们程序员工作中经常会遇到的,无论是翻阅官方文档,还是编程开发都离不开英语。有时候,我们会为了一个变量名、方法名、类名苦思冥想,常常需要使用翻译软件来起一个贴切而优美的名字。今天,给大家介绍一个简洁高效的翻译软件,使用快捷键即可快速完成翻......
  • 前端划词选中实现
    1、需求如上图,鼠标划词选中标签,选中的词自动填入到输入框中2、实现<divclass="tag-words"@mouseup="startSelectWord"><divclass="tag-word"v-for="(item,index)intagWords":key="index">{{item.text}}......
  • Pot(划词翻译) v2.0 官方版
    概述Pot是一款支持Windows、macOS、Linux的划词翻译软件,拥有DeepL、彩云小译、OpenAI等7家翻译引擎,可以整合Anki与欧陆词典的生词本,支持以SnipDo(Windows)、PopClip(MacOS)、Starry(Linux)插件的方式运行,目前最新版本2.0软件特色划词翻译:选中需要翻译的文本之后,按下......
  • js 0.02 - 0.01 - 0.01 怎么得出 0.00999999999,如何修正
    ......
  • 划词标注或打标签的实现方案
    我们有很多业务场景需要对文字打标签,有的直接划词,有的需要打标签,比如下面的动图展示。对实现思路做个总结保存数据展示start起始位置(包含)end结束位置(不包含)label打的标签text划选的为本实现思路:基于vue的数据驱动操作,不需要关心dom,只需操作数据即可1.将text文本拆分......
  • 浏览器划词翻译脚本iTranslator
    iTranslator划词翻译安装,首先浏览器要先安装暴力猴插件,搜索iTranslator安装即可使用,光标选择页面上的词语,按下T键就可以翻译,按下Y键就可以撤销翻译缺点:输入框不能直接翻译,要选择里的打开翻译才会有个输入框翻译......
  • PDF划词翻译
    PDF划词翻译一个简单的PDF划词翻译软件。Github仓库地址:https://github.com/WCX1024979076/simple_pdf_translatorGithub下载地址:https://github.com/WCX1024979076/si......
  • 软件需求设计方法学全程实例剖析幻灯片01-概述(2020.02更新)
    pdf下载地址:​​http://www.umlchina.com/training/slide.html​​......
  • Chrom谷歌翻译替代-腾讯翻译-整页翻译-划词翻译
    GoogleChrome谷歌浏览器的谷歌翻译不能用了,个人觉得腾讯翻译是一个不错的替代品,最下面是翻译效果对比图 腾讯翻译下载页面https://transmart.qq.com/zh-CN/download......
  • Java学习——10.02
     不得不说,Java真的很好上手,只不过搭建环境真的难。今天的话搞了一个喜欢的Java开发背景图,看着就心情愉悦。再加上今天idea学生认证下来,就很棒!    废话不多说进入正......