首页 > 其他分享 >js实用函数

js实用函数

时间:2023-03-13 19:12:48浏览次数:39  
标签:node 函数 url js 实用 点击 tag let id

1.批量设置元素属性,代码将所有视频音频图片设置属性,添加控制按钮,设定宽度不超过屏幕 setAttr

点击查看代码
let medias = [];
let tagAttr = {
    'video': {   'width': '100%', 'controls': 'true'   },
    'audio': { 'controls': 'true' },
    'img': { 'width': '100%' }
}
 
for (let tag of Object.entries(tagAttr)){
    console.log(tag )
    tags=document.querySelectorAll(tag[0])
    medias=medias.concat(tags)
    setAttr(tags,tag[1])
}
function setAttr(nodes, attr) {
    nodes.forEach ((node,index)=>  
        Array.from(  Object.entries(attr)).forEach((key,index)=>node.setAttribute(key[0], key[1]))
        )
}
let x=medias[0][0].width

2.获取链接 含有特定字符串 filter

点击查看代码
let links_page = Array.from(document.querySelectorAll('a')).filter((node) => { return node.href.includes('pn') })
x = links_page[0]

3.浏览器存储本地数据 用于站内传递数据(如详情页下一个播放) 获取preview类标签,个数多需要存储,少读取。localStorage

点击查看代码
let previews = document.querySelectorAll('.preview')
let previewsList, previewsDict;
if (previews.length > 5) {
    // id api 字典
    previewsDict = {};
    previewsList = new Array();
    [].forEach.call(previews, (node) => {
        let src = node.src;
        let id = node.dataset.id;
        let url;
        url = '/detail?id=' + id
        previewsDict[id] = url
        previewsList.push(id)
    })
    previewsDict['index'] = previewsList
    localStorage.setItem('preLink', JSON.stringify(previewsDict))
}
else {
    previewsDict = JSON.parse(localStorage.getItem('preLink'));
    previewsList = previewsDict['index']

}

4.点击元素网页跳转 承接3自由变量

点击查看代码
 previews.forEach((node)=> {
    node.addEventListener('click', (e) => {
        let id = e.target.dataset.id;
        window.location.href = `/detail?id=${id}`

    })
})

5.表单搜索 拼英输入结束自动跳转到搜索页 argsGet

点击查看代码

let prefixSearch='&search='
let idSearch="#search"
let rePrefixSearch=/&search=[^&]*/
// let idSearch="#sb_form_q"
// let prefixSearch='search?q='
let formInput = document.querySelector(idSearch);
//  表单内容搜索  
function toUrlSearch() {
    // ele.preventDefault()
    let base =  location.href.replace(rePrefixSearch, '')
    base = base.replace(/pn=\d+/, '')
    let s = prefixSearch + formInput.value
    if (s)
        window.location.href = base + s
}
function argsGet(url){
    if(!url)
        url=location.search
    if (url.includes('?'))
        url = url.split('?')[1]
    const urlSearchParams = new URLSearchParams(url)
    const result = Object.fromEntries(urlSearchParams.entries())
    return result
}
 
if (formInput) {
    // 请求参数写入表单
    document.addEventListener('DOMContentLoaded', ()=>{
        let r=argsGet()
        if (r.search) {
            formInput.value = r.search
        }
    })
    // 打字结束自动搜索
    formInput.addEventListener("compositionend", toUrlSearch);
}
6. 异步get请求 用于浏览器后台发送点赞申请,点击变色,根据返回信息决定颜色 fetch .style.backgroundColor
点击查看代码
let buttnons = document.querySelectorAll("button.send_href");
buttnons.forEach((node) => {
    node.addEventListener('click', (e) => {
        e.preventDefault()
        let tag=e.target
        let id = tag.dataset.id
        tag.style.backgroundColor = 'blue'
        if (!id)
            return
        let url = '/api/like?id=' + id
        fetch(url)
            .then(response => response.json())
            .then(result => {
                // 返回值处理 变色链接
                let rtext = JSON.stringify(result);
                if (rtext.includes('删除'))
                    tag.style.backgroundColor = 'white'
                else
                    tag.style.backgroundColor = 'red'
            })
    })
})
7.多击跳转下一个网页,详情页中跳转 需要3存储浏览页数据。点击计数,与上一次比超时归零,实现多击监听 根据位置可以跳转上下,e.clientY 获取点击的y坐标 getBoundingClientRect 函数用于获取标签的中心坐标
点击查看代码
nclickEvent(3, document, (e)=> {
    let id = GetRequest(location.search).id
    if (id && location.href.includes('detail')) {
        let clickY = e.clientY
        let mediaY;
        for (let i = 0; i < medias.length; i++) {
            try {
                mediaY = medias[i][0].getBoundingClientRect().y
                break
            }
            catch {

            }
        }
        let plus = 1
        if (clickY < mediaY)
            plus = -1
        let index = previewsList.indexOf(id)
        if (index === previewsList.length)
            index = 0
        let url = previewsDict[previewsList[index + plus]]
        window.location.href = url
    }
})

// 对象绑定 多击事件
function nclickEvent(n, dom, fn) {
    dom.removeEventListener('dblclick', null);
    var n = parseInt(n) < 1 ? 1 : parseInt(n),
        count = 0,
        lastTime = 0;//用于记录上次结束的时间
    var handler = function (event) {
        var currentTime = new Date().getTime();//获取本次点击的时间
        count = (currentTime - lastTime) < 300 ? count + 1 : 0;//如果本次点击的时间和上次结束时间相比大于300毫秒就把count置0
        lastTime = new Date().getTime();
        if (count >= n - 1) {
            fn(event);
            count = 0;
        }
    };
    dom.addEventListener('click', handler);
}

标签:node,函数,url,js,实用,点击,tag,let,id
From: https://www.cnblogs.com/adenosine/p/17210938.html

相关文章