Skip to content

Instantly share code, notes, and snippets.

@Xilesun
Last active October 25, 2018 08:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xilesun/2ad634888bc2995c219a83f1fc6f408b to your computer and use it in GitHub Desktop.
Save Xilesun/2ad634888bc2995c219a83f1fc6f408b to your computer and use it in GitHub Desktop.
JavaScript代码段
function addEventHandler (target, type, func) {
if (target.addEventListener) {
target.addEventListener(type, func, false);
} else if (target.attachEvent) {
target.attachEvent('on' + type, func);
} else {
target['on' + type] = func;
}
}
var addUrlParam = function(search, key, val){
var newParam = key + '=' + val,
params = '?' + newParam;
// If the "search" string exists, then build params from it
if (search) {
// Try to replace an existance instance
params = search.replace(new RegExp('([?&])' + key + '[^&]*'), '$1' + newParam);
// If nothing was replaced, then add the new param to the end
if (params === search) {
params += '&' + newParam;
}
}
return params;
};
//普通数组去重
return Array.from(new Set(arr))
//含对象数组去重
function unique (arr) {
let result = {}
let finalResult = []
for(let i = 0; i < arr.length; i++) {
result[arr[i].teacher + arr[i].name] = arr[i]
//因为arr[i].name不能重复,达到去重效果,且这里必须知晓"name"或是其他键名
}
//现在result内部都是不重复的对象了,只需要将其键值取出来转为数组即可
for (let item in result) {
finalResult.push(result[item])
}
return finalResult
}
// underscore的debouce
function restArgs(func, startIndex) {
startIndex = startIndex == null ? func.length - 1 : +startIndex
return function() {
var length = Math.max(arguments.length - startIndex, 0),
rest = Array(length),
index = 0
for ( ;index < length; index++) {
rest[index] = arguments[index + startIndex]
}
switch (startIndex) {
case 0: return func.call(this, rest)
case 1: return func.call(this, arguments[0], rest)
case 2: return func.call(this, arguments[0], arguments[1], rest)
}
var args = Array(startIndex + 1)
for (index = 0; index < startIndex; index++) {
args[index] = arguments[index]
}
args[startIndex] = rest
return func.apply(this, args)
}
}
var delay = restArgs(function(func, wait, args) {
return setTimeout(function() {
return func.apply(null, args)
}, wait)
})
function debounce(func, wait, immediate) {
var timeout, result
var later = function(context, args) {
timeout = null
if (args) result = func.apply(context, args)
}
var debounced = restArgs(function(args) {
if (timeout) clearTimeout(timeout)
if (immediate) {
var callNow = !timeout
timeout = setTimeout(later, wait)
if (callNow) result = func.apply(this, args)
} else {
timeout = delay(later, wait, this, args)
}
return result
})
debounced.cancel = function() {
clearTimeout(timeout)
timeout = null
}
return debounced
}
//Retrive array data in local json file
$.getJSON(`filename.json`).done(function (data) {
if (data) {
data.forEach(function (item, index) {
//dosomething
})
}
})
// 获取选取周围句子
const INLINE_TAGS = new Set([
// Inline text semantics
'a', 'abbr', 'b', 'bdi', 'bdo', 'br', 'cite', 'code', 'data', 'dfn', 'em', 'i',
'kbd', 'mark', 'q', 'rp', 'rt', 'rtc', 'ruby', 's', 'samp', 'small',
'span', 'strong', 'sub', 'sup', 'time', 'u', 'var', 'wbr'
])
/**
* @returns {string}
*/
function getSelectionSentence (slt) {
const sentenceHeadTester = /((\.(?![ .]))|[^.?!。?!…\r])+$/
const sentenceTailTester = /^((\.(?![ .]))|[^.?!。?!…\r])+(.)\3{0,2}/
const selection = slt
const selectedText = slt.toString()
if (!selectedText.trim()) { return '' }
var sentenceHead = ''
var sentenceTail = ''
const anchorNode = selection.anchorNode
if (anchorNode.nodeType === Node.TEXT_NODE) {
let leadingText = anchorNode.textContent.slice(0, selection.anchorOffset)
for (let node = anchorNode.previousSibling; node; node = node.previousSibling) {
if (node.nodeType === Node.TEXT_NODE) {
leadingText = node.textContent + leadingText
} else if (node.nodeType === Node.ELEMENT_NODE) {
leadingText = node.innerText + leadingText
}
}
for (
let element = anchorNode.parentElement;
element && INLINE_TAGS.has(element.tagName.toLowerCase()) && element !== document.body;
element = element.parentElement
) {
for (let el = element.previousElementSibling; el; el = el.previousElementSibling) {
leadingText = el.innerText + leadingText
}
}
sentenceHead = (leadingText.match(sentenceHeadTester) || [''])[0]
}
const focusNode = selection.focusNode
if (selection.focusNode.nodeType === Node.TEXT_NODE) {
let tailingText = selection.focusNode.textContent.slice(selection.focusOffset)
for (let node = focusNode.nextSibling; node; node = node.nextSibling) {
if (node.nodeType === Node.TEXT_NODE) {
tailingText += node.textContent
} else if (node.nodeType === Node.ELEMENT_NODE) {
tailingText += node.innerText
}
}
for (
let element = focusNode.parentElement;
element && INLINE_TAGS.has(element.tagName.toLowerCase()) && element !== document.body;
element = element.parentElement
) {
for (let el = element.nextElementSibling; el; el = el.nextElementSibling) {
tailingText += el.innerText
}
}
sentenceTail = (tailingText.match(sentenceTailTester) || [''])[0]
}
return (sentenceHead + selectedText + sentenceTail)
.replace(/(^\s+)|(\s+$)/gm, '\n') // allow one empty line & trim each line
.replace(/(^\s+)|(\s+$)/g, '') // remove heading or tailing \n
}
let slt = window.getSelection()
getSelectionSentence(slt)
/**
* JavaScript Tools
* @Qia YANG (https://imqia.me/)
* @date 2016-12-24 21:54:40
* two ways to delete an item in an array
*/
var myArray = ["a", "b", "c"];
delete myArray[0]; // => [null, "b", "c"]
myArray.splice(0, 1); // => ["b", "c"]
/**
* About Array.prototype.splice()
* Syntax:
* array.splice(start, deleteCount, item1, item2, ...)
* For example:
**/
myArray.splice(1, 0, "d"); // => ["a", "b", "d", "c"]
// 在Chrome插件中import/export本地文件
// export
var MyArray = [elem1, elem2, ....];
var _myArray = JSON.stringify(MyArray , null, 4); //indentation in json format, human readable
var vLink = document.createElement('a'),
vBlob = new Blob([_myArray], {type: "octet/stream"}),
vName = 'watever_you_like_to_call_it.json',
vUrl = window.URL.createObjectURL(vBlob);
vLink.setAttribute('href', vUrl);
vLink.setAttribute('download', vName );
vLink.click();
// import
// <input type="file" id="importOrig" accept=".json" style="display:none"/>
importOrig.addEventListener("change", importFun, false);
fakeImp.onclick = function () {importOrig.click()}
function importFun(e) {
var files = e.target.files, reader = new FileReader();
reader.onload = _imp;
reader.readAsText(files[0]);
}
function _imp() {
var _myImportedData = JSON.parse(this.result);
//here is your imported data, and from here you should know what to do with it (save it to some storage, etc.)
......
importOrig.value = ''; //make sure to clear input value after every import
}
// 分割html标签
arr = html.split(/<\/?[\w\s="/.':;#-\/\?]+>/ig)
// Remove newline
/(\r\n\t|\n|\r\t)/g
// Multiple spaces
/ +(?= )/g
// Html entities
/&[#A-Za-z0-9]+;/gi
// Script tag and its content
/<script[^>]*>(?:(?!<\/script>)[^])*<\/script>/gi
/*
获取滚动条垂直偏移量的函数
除了IE8及更早版本,其他浏览器可以使用Window对象的PageYOffset属性
同时可以通过scrollTop属性来获取。
*/
function getScrollTop(){
//IE8及更早版本没有window.pageYOffset属性
if(window.pageYOffset != null){
return window.pageYOffset;
}
//标准模式查询document.documentElement
if(document.compatMode == "CSS1Compat"){
return window.document.documentElement.scrollTop;
}
//怪异模式查询document.body
return window.document.body.scrollTop;
}
function backTop(){
var top = getScrollTop();
if (top > 0) {
//用计时器设置每隔10毫秒调用自身滚动一部分
//模拟拉动滚动条效果
//arguments.callee指向当前调用的函数本身
window.scrollTo(0, top / 1.05);
setTimeout(arguments.callee, 10);
}
}
//将函数绑定到相应事件
btn.onclick = backTop;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment