簡體   English   中英

通過js添加HTML元素時阻止IE跳轉到頁面頂部

[英]Stopping IE from jumping to top of page when HTML element is added via js

我有一個帶有 ASP:Grid 的頁面,每行都有一個小的復制按鈕,用於復制單元格內的文本。 要復制文本,我編寫了以下 javascript 函數:

var copyText = function (p_text) {
  $(".copy").append("<textarea id='test'></textarea>");
  $("#test").val(p_text);
  var cutTextarea = document.querySelector("#test");
  cutTextarea.select();
  document.execCommand("copy");
  $("#test").remove();
}

它在 Firefox 和 Chrome 中運行良好。 復制也適用於 IE11,只是它總是跳到頁面的頂部,這真的很煩人。 在 Firefox 和 Chrome 中,它停留在滾動位置。 我看到了一些類似的問題,並嘗試在附加文本區域之前保存當前位置,並在函數末尾使用以下行滾動:

var selectTop = $("body").offset().top;
$("body").scrollTop(selectTop);

$("body").offset().top 返回 0 所以它不起作用。 我找到了一些其他可能的解決方案,但無法實施它們,以便它們適用於我的案例。 希望有人能給我一個可行的解決方案:)

提前致謝!

我只是在尋找類似的答案時偶然發現了這個問題(也有復制/粘貼功能),所以即使它已經使用了大約 3 年,但我最終設法解決了這個問題:

我很幸運(我猜?)有一個位置:在我的頁面中可以訪問固定 div。 所以我正在創建的元素,我確保設置一個零大小,並將其附加到那個固定的 div,這意味着沒有發生滾動。 最終結果是這樣的:

function copyStringToClipboard(str) {
    var el = document.createElement('textarea');
    el.value = str;
    el.setAttribute('readonly', '');
    el.style = { position: 'fixed', height: 0, width: 0, padding: 0, margin: 0 };
    //create in position: fixed element to avoid re-scrolling the page in IE11
    var container = document.getElementById("fixed-position-div"); 
    container.appendChild(el);
    el.select();
    document.execCommand('copy');
    container.removeChild(el);
}

我希望可以幫助某人!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM