Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/410.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript GSAP和QuerySelector不会在动态添加的字段上触发_Javascript_Jquery_Gsap_Queryselector_Jquery Clone - Fatal编程技术网

Javascript GSAP和QuerySelector不会在动态添加的字段上触发

Javascript GSAP和QuerySelector不会在动态添加的字段上触发,javascript,jquery,gsap,queryselector,jquery-clone,Javascript,Jquery,Gsap,Queryselector,Jquery Clone,我正在试用这个代码笔中的代码,它在div中的一个输入字段上工作得非常好,该字段具有classurl input,如代码笔中所示。但是,当我将其全部放在id为wrapper的div中,并添加jquery clone函数来复制div.url-input时,它成功地复制了HTML,但所有功能都停止用于动态添加的字段。我在页面的其余部分使用jQuery,但是这个代码笔使用普通javascript 我怀疑这也是forEach循环中事件侦听器的问题。以下是我尝试过的: 我尝试了使用第21行的document

我正在试用这个代码笔中的代码,它在div中的一个输入字段上工作得非常好,该字段具有class
url input
,如代码笔中所示。但是,当我将其全部放在id为
wrapper
的div中,并添加jquery clone函数来复制
div.url-input
时,它成功地复制了HTML,但所有功能都停止用于动态添加的字段。我在页面的其余部分使用jQuery,但是这个代码笔使用普通javascript

我怀疑这也是forEach循环中事件侦听器的问题。以下是我尝试过的: 我尝试了使用第21行的
document.querySelectorAll('.url input').forEach(elem=>{

document.querySelectorAll(“#包装器”).forEach(elem=>{

然后是第23、23、25和27行,我使用了后代选择器,例如
elem.querySelector('.url input.icon')
而不是
elem.querySelector('.icon')

当我尝试上述操作时,即使是初始的
url输入
字段也停止工作,动态字段也不会启动。我如何将此代码合并到一个包装器中,以便动态添加多个
url输入
div

编辑:以下是所有代码,包括克隆过程的脚本。“模板”标记包含url输入字段的HTML模板的缩小版本,以便于克隆。为了节省空间,我还缩小了CSS样式

<html>
<head>
<style>
<!-- From https://codepen.io/aaroniker/pen/WNxoovJ -->
.url-input{--background: #fff; --border-default: #E1E6F9; --border-active: #275EFE; --text-color: #646B8C; --placeholder-color: #BBC1E1; --icon: #275EFE; --close: #646B8C; --close-light: #A6ACCD; --close-background: #EFF2FB; width: 100%; max-width: 240px; display: flex; align-items: center; position: relative; border-radius: 8px; background: var(--background); box-shadow: inset 0 0 0 var(--border-width, 1px) var(--border, var(--border-default)); transition: box-shadow 0.2s; --favicon-scale: 0; --icon-offset: 0px; --clear-x: 0px; --clear-swipe-left: 0px; --clear-swipe-x: 0; --clear-swipe: 0px; --clear-scale: 0; --clear-rotate: 0deg; --clear-opacity: 0; --clear-arrow-o: 1; --clear-arrow-x: 0px; --clear-arrow-y: 0px; --clear-arrow-offset: 4px; --clear-arrow-offset-second: 4px; --clear-line-array: 8.5px; --clear-line-offset: 27px; --clear-long-array: 8.5px; --clear-long-offset: 24px;}.url-input.clearing, .url-input:focus-within{--border-width: 1.5px; --border: var(--border-active);}.url-input.clearing{--close-background: transparent; --clear-arrow-stroke: var(--close-light);}.url-input .icon{position: absolute; left: 15px; top: 15px; pointer-events: none;}.url-input .icon svg,.url-input .icon img{display: block; width: 18px; height: 18px;}.url-input .icon svg{fill: none; stroke-width: 1.5; stroke-linecap: round; stroke-linejoin: round; stroke: var(--icon);}.url-input .icon svg path{stroke-dasharray: 24px; stroke-dashoffset: var(--icon-offset);}.url-input .icon .favicon{position: absolute; left: 0; top: 0; transform: scale(var(--favicon-scale)) translateZ(0);}.url-input .text{flex-grow: 1;}.url-input .text input{-webkit-appearance: none; line-height: 24px; background: none; border: none; outline: none; display: block; width: 100%; margin: 0; padding: 12px 12px 12px 44px; font-family: inherit; font-size: 14px; font-weight: 500; color: var(--text-color);}.url-input .text input::-moz-placeholder{color: var(--placeholder-color);}.url-input .text input:-ms-input-placeholder{color: var(--placeholder-color);}.url-input .text input::placeholder{color: var(--placeholder-color);}.url-input .clear{-webkit-appearance: none; position: relative; z-index: 1; padding: 0; margin: 12px 12px 12px 0; border: none; outline: none; background: var(--b, transparent); transition: background 0.2s; border-radius: 6px; opacity: var(--clear-opacity); transform: scale(var(--clear-scale)) translateZ(0);}.url-input .clear:before{content: ""; position: absolute; top: 0; bottom: 0; right: 12px; left: var(--clear-swipe-left); background: var(--background); transform-origin: 100% 50%; transform: translateX(var(--clear-swipe)) scaleX(var(--clear-swipe-x)) translateZ(0);}.url-input .clear svg{display: block; position: relative; z-index: 1; width: 24px; height: 24px; outline: none; cursor: pointer; fill: none; stroke-width: 1.5; stroke-linecap: round; stroke-linejoin: round; stroke: var(--close); transform: translateX(var(--clear-x)) rotate(var(--clear-rotate)) translateZ(0);}.url-input .clear svg path{transition: stroke 0.2s;}.url-input .clear svg path.arrow{stroke: var(--clear-arrow-stroke, var(--close)); stroke-dasharray: 4px; stroke-dashoffset: var(--clear-arrow-offset); opacity: var(--clear-arrow-o); transform: translate(var(--clear-arrow-x), var(--clear-arrow-y)) translateZ(0);}.url-input .clear svg path.arrow:last-child{stroke-dashoffset: var(--clear-arrow-offset-second);}.url-input .clear svg path.line{stroke-dasharray: var(--clear-line-array) 28.5px; stroke-dashoffset: var(--clear-line-offset);}.url-input .clear svg path.long{stroke: var(--clear-arrow-stroke, var(--close)); stroke-dasharray: var(--clear-long-array) 15.5px; stroke-dashoffset: var(--clear-long-offset); opacity: var(--clear-arrow-o); transform: translate(var(--clear-arrow-x), var(--clear-arrow-y)) translateZ(0);}.url-input .clear:hover{--b: var(--close-background);}
</style>
</head>

<body>
<!-- Modified from https://codepen.io/aaroniker/pen/WNxoovJ -->
<div id="wrapper">
    <a href="javascript:;" id="cloner">Make copy</a>
    <div class="url-input">
        <div class="icon">
            <svg viewBox="0 0 18 18">
                <path d="M10.05 7.95001C11.55 9.45001 11.55 11.775 10.05 13.275L7.95 15.375C6.45 16.875 4.125 16.875 2.625 15.375C1.125 13.875 1.125 11.55 2.625 10.05L4.5 8.25001" />
                <path d="M7.9502 10.05C6.4502 8.55 6.4502 6.225 7.9502 4.725L10.0502 2.625C11.5502 1.125 13.8752 1.125 15.3752 2.625C16.8752 4.125 16.8752 6.45 15.3752 7.95L13.5002 9.75" />
            </svg>
            <div class="favicon"></div>
        </div>
        <div class="text">
            <input type="text" placeholder="Your URL" />
        </div>
        <button class="clear">
            <svg viewBox="0 0 24 24">
                <path class="line" d="M2 2L22 22" />
                <path class="long" d="M9 15L20 4" />
                <path class="arrow" d="M13 11V7" />
                <path class="arrow" d="M17 11H13" />
            </svg>
        </button>
    </div>
</div>

<template id="url-template" style="display:none;">
    <div class="url-input"> <div class="icon"> <svg viewBox="0 0 18 18"> <path d="M10.05 7.95001C11.55 9.45001 11.55 11.775 10.05 13.275L7.95 15.375C6.45 16.875 4.125 16.875 2.625 15.375C1.125 13.875 1.125 11.55 2.625 10.05L4.5 8.25001"/> <path d="M7.9502 10.05C6.4502 8.55 6.4502 6.225 7.9502 4.725L10.0502 2.625C11.5502 1.125 13.8752 1.125 15.3752 2.625C16.8752 4.125 16.8752 6.45 15.3752 7.95L13.5002 9.75"/> </svg> <div class="favicon"></div></div><div class="text"> <input type="text" placeholder="Your URL"/> </div><button class="clear"> <svg viewBox="0 0 24 24"> <path class="line" d="M2 2L22 22"/> <path class="long" d="M9 15L20 4"/> <path class="arrow" d="M13 11V7"/> <path class="arrow" d="M17 11H13"/> </svg> </button> </div>
</template>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.0.5/gsap.min.js"></script>

<script>
// From https://codepen.io/aaroniker/pen/WNxoovJ
const { to, set, timeline } = gsap

function validURL(str) {
    let pattern = new RegExp('^(https?:\\/\\/)?'+
        '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+
        '((\\d{1,3}\\.){3}\\d{1,3}))'+
        '(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*'+
        '(\\?[;&a-z\\d%_.~+=-]*)?'+
        '(\\#[-a-z\\d_]*)?$','i')
    return !!pattern.test(str)
}

function delay(fn, ms) {
    let timer = 0
    return function(...args) {
        clearTimeout(timer)
        timer = setTimeout(fn.bind(this, ...args), ms || 0)
    }
}

document.querySelectorAll('.url-input').forEach(elem => {
    let icon = elem.querySelector('.icon'),
        favicon = icon.querySelector('.favicon'),
        clear = elem.querySelector('.clear'),
        input = elem.querySelector('input'),
        { classList } = elem,
        svgLine = clear.querySelector('.line'),
        svgLineProxy = new Proxy({
            x: null
        }, {
            set(target, key, value) {
                target[key] = value
                if(target.x !== null) {
                    svgLine.setAttribute('d', getPath(target.x, .1925))
                }
                return true
            },
            get(target, key) {
                return target[key]
            }
        })

    svgLineProxy.x = 0

    input.addEventListener('input', delay(e => {
        let bool = input.value.length,
            valid = validURL(input.value)
        to(elem, {
            '--clear-scale': bool ? 1 : 0,
            duration: bool ? .5 : .15,
            ease: bool ? 'elastic.out(1, .7)' : 'none'
        })
        to(elem, {
            '--clear-opacity': bool ? 1 : 0,
            duration: .15
        })
        to(elem, {
            '--icon-offset': valid ? '24px' : '0px',
            duration: .15,
            delay: valid ? 0 : .2
        })
        if(valid) {
            if(favicon.querySelector('img')) {
                favicon.querySelector('img').src = 'https://f1.allesedv.com/64/' + input.value
                return
            }
            let img = new Image()
            img.onload = () => {
                favicon.appendChild(img)
                to(elem, {
                    '--favicon-scale': 1,
                    duration: .5,
                    delay: .2,
                    ease: 'elastic.out(1, .7)'
                })
            }
            img.src = 'https://f1.allesedv.com/64/' + input.value
        } else {
            if(favicon.querySelector('img')) {
                to(elem, {
                    '--favicon-scale': 0,
                    duration: .15,
                    onComplete() {
                        favicon.querySelector('img').remove()
                    }
                })
            }
        }
    }, 250))

    clear.addEventListener('click', e => {
        classList.add('clearing')
        set(elem, {
            '--clear-swipe-left': (input.offsetWidth - 44) * -1 + 'px'
        })
        to(elem, {
            keyframes: [{
                '--clear-rotate': '45deg',
                duration: .25
            }, {
                '--clear-arrow-x': '2px',
                '--clear-arrow-y': '-2px',
                duration: .15
            }, {
                '--clear-arrow-x': '-3px',
                '--clear-arrow-y': '3px',
                '--clear-swipe': '-3px',
                duration: .15,
                onStart() {
                    to(svgLineProxy, {
                        x: 3,
                        duration: .1,
                        delay: .05
                    })
                }
            }, {
                '--clear-swipe-x': 1,
                '--clear-x': (input.offsetWidth - 32) * -1 + 'px',
                duration: .45,
                onComplete() {
                    input.value = ''
                    input.focus()
                    if(favicon.querySelector('img')) {
                        to(elem, {
                            '--favicon-scale': 0,
                            duration: .15,
                            onComplete() {
                                favicon.querySelector('img').remove()
                            }
                        })
                        to(elem, {
                            '--icon-offset': '0px',
                            '--icon-offset-line': '0px',
                            duration: .15,
                            delay: .2
                        })
                    }
                    to(elem, {
                        '--clear-arrow-offset': '4px',
                        '--clear-arrow-offset-second': '4px',
                        '--clear-line-array': '8.5px',
                        '--clear-line-offset': '27px',
                        '--clear-long-offset': '24px',
                        '--clear-rotate': '0deg',
                        '--clear-arrow-o': 1,
                        duration: 0,
                        delay: .7,
                        onStart() {
                            classList.remove('clearing')
                        }
                    })
                    to(elem, {
                        '--clear-opacity': 0,
                        duration: .2,
                        delay: .55
                    })
                    to(elem, {
                        '--clear-arrow-o': 0,
                        '--clear-arrow-x': '0px',
                        '--clear-arrow-y': '0px',
                        '--clear-swipe': '0px',
                        duration: .15
                    })
                    to(svgLineProxy, {
                        x: 0,
                        duration: .45,
                        ease: 'elastic.out(1, .75)'
                    })
                }
            }, {
                '--clear-swipe-x': 0,
                '--clear-x': '0px',
                duration: .4,
                delay: .35
            }]
        })
        to(elem, {
            '--clear-arrow-offset': '0px',
            '--clear-arrow-offset-second': '8px',
            '--clear-line-array': '28.5px',
            '--clear-line-offset': '57px',
            '--clear-long-offset': '17px',
            duration: .2
        })
    })
})

function getPoint(point, i, a, smoothing) {
    let cp = (current, previous, next, reverse) => {
            let p = previous || current,
                n = next || current,
                o = {
                    length: Math.sqrt(Math.pow(n[0] - p[0], 2) + Math.pow(n[1] - p[1], 2)),
                    angle: Math.atan2(n[1] - p[1], n[0] - p[0])
                },
                angle = o.angle + (reverse ? Math.PI : 0),
                length = o.length * smoothing;
            return [current[0] + Math.cos(angle) * length, current[1] + Math.sin(angle) * length];
        },
        cps = cp(a[i - 1], a[i - 2], point, false),
        cpe = cp(point, a[i - 1], a[i + 1], true);
    return `C ${cps[0]},${cps[1]} ${cpe[0]},${cpe[1]} ${point[0]},${point[1]}`;
}

function getPath(x, smoothing) {
    return [
        [2, 2],
        [12 - x, 12 + x],
        [22, 22]
    ].reduce((acc, point, i, a) => i === 0 ? `M ${point[0]},${point[1]}` : `${acc} ${getPoint(point, i, a, smoothing)}`, '')
}
</script>

<script>
// jQuery 3.5.1 has already been included
$('#cloner').click(function(e){
    e.preventDefault();
    let $urlTemplate = $("template#url-template").html();
    let urlCopy = $($urlTemplate).clone();
    $("#wrapper").append(urlCopy);
    $(this).blur();
})
</script>
</body>
</html>

.url输入{--背景:#fff;--边框默认值:#E1E6F9;--边框激活:#275EFE;--文本颜色:#646B8C;--占位符颜色:#BBC1E1;--图标:#275EFE;--关闭灯光:#A6ACCD;--关闭背景:#EFF2FB;宽度:100%;最大宽度:240px;显示:柔性;对齐项目:中心;位置:相对;边框半径:8px(-background);框阴影:插入0 var(--border-width,1px)var(--border,var(--border-default));过渡:框阴影0.2s;--法维康比例:0;--图标偏移量:0px;--清除-x:0px;--清除向左滑动:0px;--清除-滑动-x:0;--清除滑动:0px;--清除比例:0;--清除旋转:0deg;--清除不透明度:0;--清除箭头-o:1;--清除箭头-x:0px;--清除箭头-y:0px;--清除箭头偏移量:4px;--清除箭头第二偏移量:4px;--清除线-数组:8.5px;--清除行偏移量:27px;--清除长数组:8.5px;--清除长偏移量:24px;}.url-input.clearing.url输入:焦点在{--边框宽度:1.5px;--边框:var(--边框活动);}.url输入.清除{--关闭背景:透明;--清除箭头笔划:var(--关闭灯光);}.url输入.图标{位置:绝对;左侧:15px;顶部:15px;指针事件:无;}.url输入。图标svg,.url输入。图标img{显示:块;宽度:18px;高度:18px;}.url输入。图标svg{填充:无;笔划宽度:1.5;笔划线帽:圆形;笔划线连接:圆形;笔划:var(--图标);}.url输入。图标svg路径{笔划数组:24px;笔划偏移:var(-icon offset);}.url-input.icon.favicon{position:absolute;left:0;top:0;transform:scale(var(-favicon-scale))translateZ(0);}.url-input.text{flex-grow:1;}.url-input.text输入{-webkit外观:无;线宽:24px;背景:无;边框:无;轮廓:无;显示:块;宽度:100%;边距:0;填充:12px 12px 12px 44px;字体系列:继承;字体大小:14px;字体重量:500;颜色:var(--文本颜色);}.url输入。文本输入::-moz占位符{color:var(--占位符颜色);}.url输入.文本输入:-ms输入占位符{color:var(--placeholder color);}.url输入.文本输入::占位符{color:var(--placeholder color);}.url输入.清除{webkit外观:无;位置:相对;z索引:1;填充:0;边距:12px 12px 12px 0;边框:无;轮廓:无;背景:var(--b,透明);转换:背景0.2s;边框半径:6px;不透明度:var(--清除不透明度);转换:缩放(var(--清除缩放))translateZ(0);}.url输入。清除:在{content:”;位置:绝对;顶部:0;底部:0;右侧:12px;左侧:var(--清除向左滑动);背景:var(--背景);转换原点:100%50%;转换:translateX(var(-clear-swipe))scaleX(var(--clear-swipe-x))translateZ(0);}.url输入.clear svg{display:block;position:relative;z-index:1;width:24px;height:24px;outline:none;游标:指针;fill:none;笔划宽度:1.5;笔划linecap:round;笔划连接:round;笔划:var(--close);transform:translateX(var(--clear-x))旋转(var(-clear rotate))translateZ(0);}.url输入。清除svg路径{transition:stroke 0.2s;}.url输入。清除svg路径。箭头{stroke:var(--clear-stroke,var(--close));stroke-dasharray:4px;stroke-dashoffset:var(--clear-arrow-o);不透明度:var(--clear-arrow-o);转换:translateZ(0);}.url输入。清除svg路径。箭头:最后一个子项{stroke dashoffset:var(-clear arrow offset second);}.url输入。清除svg路径。行{stroke dasharray:var(-clear line array)28.5px;stroke dashoffset:var(-clear line offset);}.url输入。清除svg路径。长{stroke:var(-clear arrow-arrow,var(-close));stroke dasharray:var(-clear long array)15.5px;笔划dashoffset:var(--clear long offset);不透明度:var(--clear-arrow-o);转换:translate(var(--clear-arrow-x),var(--clear-arrow-y))translateZ(0);}.url输入。清除:悬停{--b:var(--close background);}
//从https://codepen.io/aaroniker/pen/WNxoovJ
常数{to,set,timeline}=gsap
函数validul(str){
let pattern=new RegExp('^(https?:\\/\\\/)?'+
“(([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\)+[a-z]{2,}124;”+
“(\\d{1,3}\\){3}\\d{1,3}”)”+
“(\\:\\d+)(\\/[-a-z\\d%.~+]*)*”+
function initInput() {
  document.querySelectorAll(".url-input").forEach((elem) => {
  :
  :
        to(elem, {
          "--clear-arrow-offset": "0px",
          "--clear-arrow-offset-second": "8px",
          "--clear-line-array": "28.5px",
          "--clear-line-offset": "57px",
          "--clear-long-offset": "17px",
          duration: 0.2,
        });
      });//end clear.addEventListener
    });//end queryselectorAll
}
jQuery(function () {

  const { to, set, timeline } = gsap;
  initInput();
  $("#cloner").click(function (e) {
    e.preventDefault();
    let $urlTemplate = $("template#url-template").html();
    let urlCopy = $($urlTemplate).clone();
    $("#wrapper").append(urlCopy);
    $(this).blur();
    initInput();
  });
  :
  :