gpt4 book ai didi

javascript - JavaScript : Code-Selection - What's wrong?

转载 作者:行者123 更新时间:2023-12-03 08:30:56 25 4
gpt4 key购买 nike

<!DOCTYPE html>
<html>
<head>
<title>Select Code</title>
<meta charset="UTF-8">
<script type="text/javascript">
window.onload = function() {
function selectCode(a) {

// Get ID of Code Block
var e = a.parentNode.parentNode.getElementsByTagName('code')[0];

// Not IE or IE9+
if (window.getSelection) {
var s = window.getSelection();
if (s.setBaseAndExtent) {
s.setBaseAndExtent(e, 0, e, e.innerText.length - 1);
}

// Firefox and Opera
else {
if (window.opera && e.innerHTML.substring(e.innerHTML.length - 4) == '<br>') {
e.innerHTML = e.innerHTML + '&nbsp;';
}
var r = document.createRange();
r.selectNodeContents(e);
s.removeAllRanges();
s.addRange(r);
}
}

// Some older browsers
else if (document.getSelection) {
var s = document.getSelection();
var r = document.createRange();
r.selectNodeContents(e);
s.removeAllRanges();
s.addRange(r);
}

// IE
else if (document.selection) {
var r = document.body.createTextRange();
r.moveToElementText(e);
r.select();
}
};
}
</script>
</head>
<body>
<a onclick="selectCode(this); return false;" href="#">Select all</a>
<code>Some Code</code>
</body>
</html>

有人知道出什么事了吗?就是行不通。 :-(

最佳答案

我刚刚删除了window.onload

在这里查看工作代码http://jsfiddle.net/5n4cw/

<a onclick="selectCode(this);" href="#">Select all</a>
<code>Some Code</code>


<script type='text/javascript'>

function selectCode(a) {

// Get ID of Code Block
var e = a.parentNode.parentNode.getElementsByTagName('code')[0];
// Not IE or IE9+
if (window.getSelection) {
var s = window.getSelection();
if (s.setBaseAndExtent) {
s.setBaseAndExtent(e, 0, e, e.innerText.length - 1);
}

// Firefox and Opera
else {
if (window.opera && e.innerHTML.substring(e.innerHTML.length - 4) == '<br>') {
e.innerHTML = e.innerHTML + '&nbsp;';
}
var r = document.createRange();
r.selectNodeContents(e);
s.removeAllRanges();
s.addRange(r);
}
}

// Some older browsers
else if (document.getSelection) {
var s = document.getSelection();
var r = document.createRange();
r.selectNodeContents(e);
s.removeAllRanges();
s.addRange(r);
}

// IE
else if (document.selection) {
var r = document.body.createTextRange();
r.moveToElementText(e);
r.select();
}
}

</script>

关于javascript - JavaScript : Code-Selection - What's wrong?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15790032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com