简体   繁体   English

为什么 javascript 正在创建自己的元素?

[英]Why javascript is creating it's own elements?

Hey am a new web developer and I am writing a html, css and javascript.嘿,我是一名新的 web 开发人员,我正在编写 html、css 和 ZDE9B9ED78D7E2E911DCEEFFEE7802E。 I have created a "copy" button to copy the text inside the <p> element and a alert that the text is copied.我创建了一个“复制”按钮来复制<p>元素内的文本,并警告该文本已被复制。

 buttons.forEach((copystatus) => { copystatus.addEventListener('click', (e) => { const copylatest = e.target.closest(".latestatus").querySelector("p").innerText; const copyText = document.createElement('textarea'); copyText.style.width = "0"; copyText.style.height = "0"; copyText.style.outline = "none"; copyText.style.border = "none"; copyText.value = copylatest; document.body.appendChild(copyText); copyText.select(); document.execCommand('copy'); document.body.removeChild(copyText); copyalert.style.visibility = "visible" e.target.closest(".latestatus").querySelector("p").appendChild(copyalert); setTimeout(function() { copyalert.style.visibility = "hidden" }, 700); }) })
 .randomStatusCopyAlert { position: relative; background-color: #18b495; color: #ffffff; padding: 10px 10px; border-radius: 5px; z-index: 2; visibility: hidden; height: 45px; float: right; bottom: 2px; left: 4%; }.randomStatusCopyAlert:before { content: ""; position: absolute; height: 10px; width: 10px; background-color: #18b495; left: -5px; z-index: 1; transform: rotate(45deg); top: 39%; }
 <div class="mainStatus"> <h2 class="statusHeading">Latest English Status</h2> <div class="allStatus"> <div class="block"> <div class="latestatus"> <p>Life is good when you have books</p> <div class="flex"><button class="copystatus btn">Copy</button> <span class="randomStatusCopyAlert show">Copied.</span></div> </div> <div class="latestatus"> <p>Google is a open source library by Larry Page and Sergey Brin!</p> <div class="flex"><button class="copystatus btn">Copy</button> <span class="randomStatusCopyAlert">Copied!</span></div> </div> </div> <div class="block"> <div class="latestatus"> <p>Cats are better than dogs.</p> <div class="flex"><button class="copystatus btn">Copy</button> <span class="randomStatusCopyAlert">Copied!</span></div> </div> <div class="latestatus"> <p>Ferrets are better than rats</p> <div class="flex"><button class="copystatus btn">Copy</button> <span class="randomStatusCopyAlert">Copied!</span></div> </div> </div> </div> </div>

My main intention is to make visible the respective <span class="randomStatusCopyAlert">Copied!</span> when respective <button class="copystatus btn">Copy</button> is clicked.我的主要目的是在单击相应的<button class="copystatus btn">Copy</button>时使相应的<span class="randomStatusCopyAlert">Copied!</span>可见。 Although the code is working correctly but the javascript creats itself span and display it.虽然代码工作正常,但 javascript 会创建自己的跨度并显示它。 See I will share some pics so that if I make ". randomStatusCopyAlert" myself visible.看我会分享一些照片,这样如果我让“.randomStatusCopyAlert”自己可见。 [![See Now the the span is place correctly][1]][1] [![现在查看跨度正确放置][1]][1]

Now the span is placed correctly.现在跨度已正确放置。 When it is done by the above javascript [![the span change its position and goes into当它由上述 javascript [![跨度更改其 position 并进入

elements when I used html code inspection tool][2]][2]我使用html代码检查工具时的元素][2]][2]

The span position is changed.跨度 position 已更改。 [1]: https://i.stack.imgur.com/aNevS.png [2]: https://i.stack.imgur.com/b0az4.png [1]: https://i.stack.imgur.com/aNevS.png [2]: https://i.stack.imgur.com/b0az4.png

I tried to replicate your code into a simpler structure just for demonstration purpose我试图将您的代码复制到一个更简单的结构中,仅用于演示目的

Here is the HTML这是 HTML

<div class="statuses-container">
  <h2 class="statuses-heading">Latest English Status</h2>
  <div class="statuses">
    <div class="status">
      <p class="status-text">Life is good when you have books</p>
      <div class="status-copy-btn-container">
        <button class="status-copy-btn btn">Copy</button>
      </div>
    </div>
    <div class="status">
      <p class="status-text">Google is an open source library by Larry Page and Sergey Brin!</p>
      <div class="status-copy-btn-container">
        <button class="status-copy-btn btn">Copy</button>
      </div>
    </div>
    <div class="status">
      <p class="status-text">Cats are better than dogs.</p>
      <div class="status-copy-btn-container">
        <button class="status-copy-btn btn">Copy</button>
      </div>
    </div>
  </div>
</div>

Feel free to change the class names as you wish, I've changed them because I find it easier to read like this.随意更改 class 名称,因为我发现这样更容易阅读。 Some of the divs were removed, because I think they were not really necessary in achieving this result.删除了一些 div,因为我认为它们对于实现此结果并不是真正必要的。

Please notice that I've removed the span which indicated that the text was copied to clipboard.请注意,我已经删除了表明文本已复制到剪贴板的跨度。 It is not necessary, because maybe at some point you will decide to change the message, and you will have to change it everywhere.这不是必需的,因为也许在某个时候您会决定更改消息,并且您将不得不在任何地方进行更改。 Now, that label saying that the text was copied will be inserted using JS.现在,label 说文本被复制将使用 JS 插入。

Here is the CSS:这是 CSS:

status-copy-alert {
 position: relative;
 background-color: #18b495;
 color: #ffffff;
 padding: 10px 10px;
 border-radius: 5px;
 left: 8px;
}
.status-copy-alert:before{
 content:"";
 position: absolute;
 height: 10px;
 width: 10px;
 background-color: #18b495;
 left: -5px;
 transform: rotate(45deg);
 top: 39%;
}

Some of the properties here were removed as well, because they were not necessary.这里的一些属性也被删除了,因为它们不是必需的。 Since we are adding the span dynamically using the JS, there is no need for the span to be hidden in the beginning.由于我们是使用 JS 动态添加 span,因此无需在开始时将 span 隐藏。

Here is the JS:这是JS:

var buttons = document.getElementsByClassName('status-copy-btn');

for (let button of buttons) {
  button.addEventListener('click', function() {
     let statusElement = this.closest('.status');
     let textToCopy = statusElement.getElementsByClassName('status-text')[0].innerHTML;
    
    copyTextToClipboard(textToCopy);
    addCopyStatusAlert(this.parentNode);
  });
}

function copyTextToClipboard(text) {
  const copyText = document.createElement('textarea');
  copyText.style.position="absolute";
  copyText.style.display="none";
  copyText.value = text;

  document.body.appendChild(copyText);
  copyText.select();
  document.execCommand('copy');
  document.body.removeChild(copyText);
}

function addCopyStatusAlert(element) {
  if (!element.getElementsByClassName('status-copy-alert').length) {
    let copyAlertElement = document.createElement('span');
    copyAlertElement.classList.add('status-copy-alert')
    let copyMessage = document.createTextNode('Copied!');
    copyAlertElement.appendChild(copyMessage);

    element.appendChild(copyAlertElement);

    setTimeout(function() {
      element.removeChild(copyAlertElement);
    }, 700);
  }
}

I've taken all of the buttons and added a click listener on them.我已经使用了所有按钮并在它们上添加了一个click监听器。 When it gets clicked, we take the entire status element and get the p element inside it.当它被点击时,我们获取整个状态元素并获取其中的p元素。 We pass the text of the p element to copyTextToClipboard function.我们将p元素的文本传递给copyTextToClipboard function。 Here is only the logic needed for copying the text to clipboard and nothing else.这里只是将文本复制到剪贴板所需的逻辑,仅此而已。

The addCopyStatusAlert function is used just to append a newly created span as a sibling to the button. addCopyStatusAlert function 仅用于 append 一个新创建的span作为按钮的兄弟。 And after a short timeout, it gets completely deleted from the DOM.在短暂的超时后,它会从 DOM 中完全删除。

Here is the link to the pen i've created on CodePen for this.这是我在 CodePen 上为此创建的笔的链接 Feel free to experiment with it there.随意在那里进行试验。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM