如何在此弹出窗口中获取/查看所选文本?所以这可以看出将要共享的文本 [英] How to get / view selected text on this popup, ? so this can be view that what text is going to be share

查看:28
本文介绍了如何在此弹出窗口中获取/查看所选文本?所以这可以看出将要共享的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在此弹出窗口中获取/查看所选文本?所以这可以查看将要共享的文本.你好亲爱的 stackoverflow 社区,请帮我解决这个问题我想在此弹出窗口上显示可共享的文本,以便可以查看将要共享的文本.我的主要目的是在这个弹出 div 上显示选定的文本.

const selectableTextArea = document.querySelectorAll(".selectable-text-area");const twitterShareBtn = document.querySelector("#twitter-share-btn");selectableTextArea.forEach(elem => {elem.addEventListener("mouseup", selectableTextAreaMouseUp);});twitterShareBtn.addEventListener("点击", twitterShareBtnClick);document.addEventListener("mousedown", documentMouseDown);函数 selectableTextAreaMouseUp(event) {setTimeout(() => {//为了避免一些奇怪的行为...const selectedText = window.getSelection().toString().trim();if(selectedText.length) {const x = event.pageX;const y = event.pageY;const twitterShareBtnWidth = Number(getComputedStyle(twitterShareBtn).width.slice(0,-2));const twitterShareBtnHeight = Number(getComputedStyle(twitterShareBtn).height.slice(0,-2));if(document.activeElement !== twitterShareBtn) {twitterShareBtn.style.left = `${x - twitterShareBtnWidth*0.5}px`;twitterShareBtn.style.top = `${y - twitterShareBtnHeight*1.25}px`;twitterShareBtn.style.display = "block";twitterShareBtn.classList.add("btnEntrance");}别的 {twitterShareBtn.style.left = `${x-twitterShareBtnWidth*0.5}px`;twitterShareBtn.style.top = `${y-twitterShareBtnHeight*0.5}px`;}}}, 0);}函数 documentMouseDown(event) {if(event.target.id!=="twitter-share-btn" && getComputedStyle(twitterShareBtn).display==="block") {twitterShareBtn.style.display = "none";twitterShareBtn.classList.remove("btnEntrance");window.getSelection().empty();}}函数 twitterShareBtnClick(事件){const selectedText = window.getSelection().toString().trim();if(selectedText.length) {//一般推特分享网址:https://twitter.com/intent/tweet?text={title}&url={url}&hashtags={hash_tags}&via={user_id}const twitterShareUrl = "https://twitter.com/intent/tweet";const text = `${encodeURIComponent(selectedText)}`;const currentUrl = encodeURIComponent(window.location.href);const hashtags = "helloworld, test, testing";const via = "CodingJrney";window.open(`${twitterShareUrl}?text="${text}"&url=${currentUrl}&hashtags=${hashtags}&via=${via}`);//或者,我们可以在文本"字段中包含所有内容 ->更多空间来自定义推文://window.open(`${twitterShareUrl}?text="${text}" by @${via} ${hashtags.split(",").map(h => "%23"+h.trim()).join(" ")} ${currentUrl}`);//我们还可以指定新的窗口功能://const newWindowOptions = "height=400,width=550,top=0,left=0,resizable=yes,scrollbars=yes";//window.open(`${twitterShareUrl}?text="${text}"&url=${currentUrl}&hashtags=${hashtags}&via=${via}`, "ShareOnTwitter",新窗口选项);}}

* {填充:0;边距:0;box-sizing: 边框框;}身体 {字体系列:Arial、Helvetica、sans-serif;背景色:#fff;颜色:#333;字体大小:1.25rem;}.容器 {填充:1.5rem 10rem;}h1{字体大小:3rem;保证金:1.25rem 0;}h2{字体大小:2rem;}小时{边距:3rem 0;边框:0;高度:1px;背景:线性梯度(向右,rgba(0, 0, 0, 0.25), rgba(0, 0, 0, 0.75), rgba(0, 0, 0, 0.25));}p{底边距:2rem;行高:1.75rem;}#twitter-share-btn {宽度:30%;高度:30%;字体大小:1rem;颜色:#56b8f5;背景色:#fff;光标:指针;边框:2px 实心 #56b8f5;位置:绝对;顶部:0;左:0;z-索引:10;显示:无;过渡:颜色 0.2s,背景颜色 0.2s 渐出;box-shadow: 0px 0px 1px 5000px rgba(0,0,0,0.8);}#twitter-share-btn:悬停{颜色:#fff;背景色:#56b8f5;}#twitter-share-btn我{指针事件:无;}.btn入口{动画持续时间:0.2s;动画填充模式:两者;动画名称:btnEntrance;}@keyframes btnEntrance {/* 放大 */0% {不透明度:0;变换:scale3d(0.3, 0.3, 0.3);}100% {不透明度:1;}}@media(最大宽度:992px){.container { 填充:1.25rem 6rem;}h1 { 字体大小:2.5rem;}h2 { 字体大小:1.75rem;}}@media(最大宽度:768px){html { 字体大小:12px;}.container { 填充:1rem 3rem;}h1 { 字体大小:2rem;}h2 { 字体大小:1.5rem;}hr { 边距:1.5rem 0;}}

<h2 class="selectable-text-area">选择要分享的文字</h2><小时><div class="selectable-text-area"><p>Lorem ipsum dolor,坐享其成.Recusandae pariatur eos aperiam saepe、beatae necessitatibus exercitationem、nemo、sit Provident possimus debitis modi eligendi repellat iure vitae perferendis?Recusandae accusamus placeat velit itaque quis fuga laudantium debitis, ab eaque voluptatum illo esse incidunt!Quia tempore explicabo sint Laboriosam rerum rerum nihil voluptates voluptatibus voluptate iure.Earum magnam blanditiis voluptates quod exercitationem reiciendis, iure qui ducimus similique impedit nemo est, quisquam facere id adipisci harum tenetur consequuntur illum saepe laudantium.Suscipit facilis corporis natus natus aperiam!Reprehenderit hic quia natus nisi similique quod fugiat, architecto autem deleniti unde commodi accusamus modi voluptate?</p>

<div id="twitter-share-btn">在 Twitter 上分享:_ _在这里我想显示将要分享的文本(表示选定的文本)"_ _</div>

提前致谢.我的主要目的是在这个弹出 div 上显示选定的文本.

解决方案

您需要使用 innerHTMLtextContent 属性.

请参阅以下示例代码片段.

const container = document.querySelector('.selectable-text-area');const popupContainer = document.querySelector('.popupContainer');container.addEventListener('mouseup', (e) => {const selectedText = window.getSelection().toString();如果(选择文本){showPopup(selectedText);}});popupContainer.addEventListener('click', (event) => {if (event.target.matches('.popupContainer')) {popupContainer.classList.remove('show');}});功能 showPopup(selectedText) {//将选中的文本设置为弹出元素内的 htmldocument.querySelector('.popup').innerHTML = selectedText;popupContainer.classList.add('show');}

body {边距:0;}.selectable-text-area {边距:0 10px;}.popupContainer {位置:固定;宽度:100vw;高度:100vh;背景:rgba(0, 0, 0, 0.7);顶部:0;显示:无;对齐项目:居中;对齐内容:居中;}.展示 {显示:弹性;}.弹出 {背景:#fff;填充:10px;边框半径:3px;box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);宽度:80%;}

<p>plz 帮我解决这个问题,我想在这个弹出窗口上显示可共享的文本,以便它可以查看将要共享的文本.我的主要目的是在这个弹出 div 上显示选定的文本</p>

<div class="popupContainer"><div class="popup"></div>

How to get / view selected text on this popup, ? so this can be view that what text is going to be share. Hello dear stackoverflow community, plz help me to make this solve i want to show sharable text on this popup so that it can be view that what text is going to be share. my main purpose is that to display selected text on this popup div.

const selectableTextArea = document.querySelectorAll(".selectable-text-area");
const twitterShareBtn = document.querySelector("#twitter-share-btn");

selectableTextArea.forEach(elem => {
  elem.addEventListener("mouseup", selectableTextAreaMouseUp);
});

twitterShareBtn.addEventListener("click", twitterShareBtnClick);

document.addEventListener("mousedown", documentMouseDown);

function selectableTextAreaMouseUp(event) {
  setTimeout(() => { // In order to avoid some weird behavior...
    const selectedText = window.getSelection().toString().trim();
    if(selectedText.length) { 
      const x = event.pageX;
      const y = event.pageY;
      const twitterShareBtnWidth = Number(getComputedStyle(twitterShareBtn).width.slice(0,-2));
      const twitterShareBtnHeight = Number(getComputedStyle(twitterShareBtn).height.slice(0,-2));

      if(document.activeElement !== twitterShareBtn) {
        twitterShareBtn.style.left = `${x - twitterShareBtnWidth*0.5}px`;
        twitterShareBtn.style.top = `${y - twitterShareBtnHeight*1.25}px`;
        twitterShareBtn.style.display = "block";
        twitterShareBtn.classList.add("btnEntrance");
      }
      else {
        twitterShareBtn.style.left = `${x-twitterShareBtnWidth*0.5}px`;
        twitterShareBtn.style.top = `${y-twitterShareBtnHeight*0.5}px`;
      }
    }    
  }, 0);
}

function documentMouseDown(event) {
  if(event.target.id!=="twitter-share-btn" && getComputedStyle(twitterShareBtn).display==="block") {
    twitterShareBtn.style.display = "none";
    twitterShareBtn.classList.remove("btnEntrance");
    window.getSelection().empty();
  }
}

function twitterShareBtnClick(event) {
  const selectedText = window.getSelection().toString().trim();
  if(selectedText.length) {
    // General Twitter Share URL: https://twitter.com/intent/tweet?text={title}&url={url}&hashtags={hash_tags}&via={user_id}
    const twitterShareUrl = "https://twitter.com/intent/tweet";
    const text = `${encodeURIComponent(selectedText)}`;
    const currentUrl = encodeURIComponent(window.location.href);
    const hashtags = "helloworld, test, testing";
    const via = "CodingJrney";
    window.open(`${twitterShareUrl}?text="${text}"&url=${currentUrl}&hashtags=${hashtags}&via=${via}`);
    
    // Alternatively, we could include everything in the "text" field -> more room to customize the tweet:
    // window.open(`${twitterShareUrl}?text="${text}" by @${via} ${hashtags.split(",").map(h => "%23"+h.trim()).join(" ")} ${currentUrl}`);
    
    // We could also specify new window features:
    // const newWindowOptions = "height=400,width=550,top=0,left=0,resizable=yes,scrollbars=yes";
    // window.open(`${twitterShareUrl}?text="${text}"&url=${currentUrl}&hashtags=${hashtags}&via=${via}`, "ShareOnTwitter", newWindowOptions);
  }
}

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
body {
  font-family: Arial, Helvetica, sans-serif;
  background-color: #fff;
  color: #333;
  font-size: 1.25rem;
}
.container {
  padding: 1.5rem 10rem;
}
h1 {
  font-size: 3rem;
  margin: 1.25rem 0;
}
h2 {
  font-size: 2rem;
}
hr {
  margin: 3rem 0;
  border: 0;
  height: 1px;
  background: linear-gradient(to right, rgba(0, 0, 0, 0.25), rgba(0, 0, 0, 0.75), rgba(0, 0, 0, 0.25)); 
}
p {
  margin-bottom: 2rem;
  line-height: 1.75rem;
}
#twitter-share-btn {
    width: 30%;
    height: 30%;
    font-size: 1rem;
    color: #56b8f5;
    background-color: #fff;
    cursor: pointer;
    border: 2px solid #56b8f5;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 10;
  display: none;
  transition: color 0.2s, background-color 0.2s ease-in-out;
  box-shadow: 0px 0px 1px 5000px rgba(0,0,0,0.8);
}
#twitter-share-btn:hover {
  color: #fff;
  background-color: #56b8f5;
}
#twitter-share-btn i {
  pointer-events: none;
}
.btnEntrance {
  animation-duration: 0.2s;
  animation-fill-mode: both;
  animation-name: btnEntrance;
}
@keyframes btnEntrance { /* zoomIn */
  0% {
    opacity: 0;
    transform: scale3d(0.3, 0.3, 0.3);
  }
  100% {
    opacity: 1;
  }    
}

@media(max-width: 992px) {
  .container { padding: 1.25rem 6rem; }
  h1 { font-size: 2.5rem; }
  h2 { font-size: 1.75rem; }
}
@media(max-width:768px) {
  html { font-size: 12px; }
  .container { padding: 1rem 3rem; }
  h1 { font-size: 2rem; }
  h2 { font-size: 1.5rem; }
  hr { margin: 1.5rem 0; }
}

<h2 class="selectable-text-area">Select the text you want to share</h2>
  <hr>
  <div class="selectable-text-area">
    <p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Recusandae pariatur eos aperiam saepe, beatae necessitatibus exercitationem, nemo, sit provident possimus debitis modi eligendi repellat iure vitae perferendis? Recusandae accusamus placeat velit itaque quis fuga laudantium debitis, ab eaque voluptatum illo esse incidunt! Quia tempore explicabo sint laboriosam rerum nihil voluptates voluptatibus voluptate iure. Earum magnam blanditiis voluptates quod ex exercitationem reiciendis, iure qui ducimus similique impedit nemo est, quisquam facere id adipisci harum tenetur consequuntur illum saepe laudantium. Suscipit facilis corporis natus aperiam! Reprehenderit hic quia natus nisi similique quod fugiat, architecto autem deleniti unde commodi accusamus modi voluptate?</p>
    
  </div>
</div>
<div id="twitter-share-btn">Share This on Twitter: _ _"here i want to show that what text is going to share (means selected text)" _ _</div>

thanks in advance. my main purpose is that to display selected text on this popup div.

解决方案

You need to set the selected text as text content of the pop-up element using either innerHTML or textContent property.

See the following example code snippet.

const container = document.querySelector('.selectable-text-area');
const popupContainer = document.querySelector('.popupContainer');

container.addEventListener('mouseup', (e) => {
  const selectedText = window.getSelection().toString();
  if (selectedText) {
    showPopup(selectedText);
  }
});

popupContainer.addEventListener('click', (event) => {
  if (event.target.matches('.popupContainer')) {
    popupContainer.classList.remove('show');
  }
});

function showPopup(selectedText) {
  // set the selected text as html inside popup element
  document.querySelector('.popup').innerHTML = selectedText;
  popupContainer.classList.add('show');
}

body {
  margin: 0;
}

.selectable-text-area {
  margin: 0 10px;
}

.popupContainer {
  position: fixed;
  width: 100vw;
  height: 100vh;
  background: rgba(0, 0, 0, 0.7);
  top: 0;
  display: none;
  align-items: center;
  justify-content: center;
}

.show {
  display: flex;
}

.popup {
  background: #fff;
  padding: 10px;
  border-radius: 3px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.3);
  width: 80%;
}

<div class="selectable-text-area">
  <p>plz help me to make this solve i want to show sharable text on this popup so that it can be view that what text is going to be share. my main purpose is that to display selected text on this popup div</p>
</div>

<div class="popupContainer">
  <div class="popup"></div>
</div>

这篇关于如何在此弹出窗口中获取/查看所选文本?所以这可以看出将要共享的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆