日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

自定义处理网页选区字符并实时显示(js)

發布時間:2024/8/23 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 自定义处理网页选区字符并实时显示(js) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

概述

瀏覽網頁的時候,可能需要去數一下某段文字的字符數量,或者需要對選中內容做些實時翻譯,比如進制的轉化,可以使用腳本做個簡單的實時翻譯。

效果

選中內容,并且鼠標移動時會在左下角顯示翻譯后的結果。示例為翻譯二進制十進值

使用方式

  • 打開開發者工具
  • 復制以下方法到控制臺
  • 執行方法,如果需要自定義處理結果,則第一個參數不為空
  • /*** 顯示頁面選中字符的長度,可修改處理結果* @param simple 是否使用簡單的事件處理邏輯*/ function getSelectionText(simple = true, render) {//監聽范圍為當下documentlet el = document.body;//添加顯示元素let el_num = document.getElementById('selectionNum');if (!el_num) {el_num = document.createElement('div');el_num.setAttribute('id', 'selectionNum');el_num.style = `position: fixed;left: 0px;bottom: 0px;width: 100px;height: 20px;line-height: 20px;border: 1px solid rgb(0, 0, 0);background: rgb(255, 255, 255);`;el.appendChild(el_num)}let text;let paint = () => {//自行修改輸出的內容text = document.getSelection().toString();el_num.innerHTML = typeof render == 'function'? render(text):text.length;};let shower = window.shower || {};//移除上次添加的事件el.removeEventListener('mousedown', shower.mouseDownHandle);el.removeEventListener('mousemove', shower.mouseMoveHandle);el.removeEventListener('mouseup', shower.mouseUpHandle);//簡單邏輯只使用mousemove 否則使用 mousedown mouseup mousemoveif (simple) {shower.mouseMoveHandle = () => paint();} else {shower.readyShow = false;shower.mouseMoveHandle = () => shower.readyShow && paint();shower.mouseDownHandle = () => {shower.readyShow = true;el.addEventListener('mouseup', shower.mouseUpHandle);el.addEventListener('mousemove', shower.mouseMoveHandle);};shower.mouseUpHandle = () => {shower.readyShow = false;el.removeEventListener('mousemove', shower.mouseMoveHandle);el.removeEventListener('mouseup', shower.mouseUpHandle);};}window.shower = shower;el.addEventListener('mousemove', shower.mouseMoveHandle);el.addEventListener('mousedown', shower.mouseDownHandle) }

    總結

    以上是生活随笔為你收集整理的自定义处理网页选区字符并实时显示(js)的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。