简体   繁体   English

通过js添加HTML元素时阻止IE跳转到页面顶部

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

I have a page with an ASP:Grid with a small copy button in each line to copy the text inside the cell.我有一个带有 ASP:Grid 的页面,每行都有一个小的复制按钮,用于复制单元格内的文本。 To copy the text I wrote the following javascript function:要复制文本,我编写了以下 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();
}

It works perfectly fine in Firefox and Chrome.它在 Firefox 和 Chrome 中运行良好。 The copying also works for IE11 except that it always jumps to the top of the page which is really annoying.复制也适用于 IE11,只是它总是跳到页面的顶部,这真的很烦人。 In Firefox and Chrome it stays at the scrolled position.在 Firefox 和 Chrome 中,它停留在滚动位置。 I saw some similar problems and tried to save the current position before I append my textarea and to scroll there at the end of the function with these lines:我看到了一些类似的问题,并尝试在附加文本区域之前保存当前位置,并在函数末尾使用以下行滚动:

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

$("body").offset().top returns 0 so it does not work. $("body").offset().top 返回 0 所以它不起作用。 I found some other possible solutions but was not able to implement them so that they would work for my case.我找到了一些其他可能的解决方案,但无法实施它们,以便它们适用于我的案例。 Hope someone can give me a working solution :)希望有人能给我一个可行的解决方案:)

Thanks in advance!提前致谢!

I just stumbled on this question while looking for a similar answer (with a copy/paste function as well), so even though it is about 3 years old, here's how I finally managed to solve it:我只是在寻找类似的答案时偶然发现了这个问题(也有复制/粘贴功能),所以即使它已经使用了大约 3 年,但我最终设法解决了这个问题:

I was lucky enough (I guess?) to have a position: fixed div accessible in my page.我很幸运(我猜?)有一个位置:在我的页面中可以访问固定 div。 So the element I was creating, I made sure to set a zero size, and appended it to that fixed div, which meant no scrolling happened.所以我正在创建的元素,我确保设置一个零大小,并将其附加到那个固定的 div,这意味着没有发生滚动。 End result being something like this:最终结果是这样的:

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);
}

I hope that can help someone!我希望可以帮助某人!

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

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