代码之家  ›  专栏  ›  技术社区  ›  vrintle Jake

从锚定标记中删除默认url

  •  0
  • vrintle Jake  · 技术社区  · 6 年前

    我有下面的代码输入 链接 从用户创建 anchor href = link

    <html>
    <head>
        <title>Page Title</title>
        <style>
            #text-input {
                border-left: 4px solid green;
                text-indent: 12px;
            }
        </style>
    </head>
    <body>
        <p>Enter a link</p>
        <div id="text-input" contenteditable="true"></div>
        
        <script>
          let div = document.getElementById('text-input');
          let anchor;
    
          div.addEventListener('blur', event => {
            let text = div.innerText;
            div.innerText = '';
            anchor = document.createElement('a');
            div.appendChild(anchor);
            anchor.innerText = text;
            anchor.href = text;
            
            // The below line logs the actual link of the anchor tag
            console.log(anchor.href);
          });
        </script>
    </body>
    </html>

    3 回复  |  直到 6 年前
        1
  •  2
  •   Piero    6 年前

        2
  •  2
  •   Suresh    6 年前

    根据您的默认要求,您可以将https或http附加到输入数据。

     anchor.innerText = text;       
                if(text.indexOf('http://')!=0 || text.indexOf('https://')!=0){
                    text = "http://"+text;  //default http(or) https
                }
                 anchor.href = text;
    
        3
  •  1
  •   Christopher Pelayo    6 年前

    <html>
    <head>
        <title>Page Title</title>
        <style>
            #text-input {
                border-left: 4px solid green;
                text-indent: 12px;
            }
        </style>
    </head>
    <body>
        <p>Enter a link</p>
        <div id="text-input" contenteditable="true"></div>
        
        <script>
          let div = document.getElementById('text-input');
          let anchor;
    
          div.addEventListener('blur', event => {
            let text = div.innerText;
            div.innerText = '';
            anchor = document.createElement('a');
            div.appendChild(anchor);
            anchor.innerText = text;
            anchor.href = 'http://'+text;
            
            // The below line logs the actual link of the anchor tag
            console.log(anchor.href);
          });
        </script>
    </body>
    </html>