如何清除间隔+消息并将其替换为链接。
下面的代码将在10秒后在新窗口中打开一个链接。当我回到该页面时,显示消息您将在0秒内重定向
我想要的是10秒钟后(在新标签页中打开链接之后),计数器和消息将替换为新的消息和链接。即如果您未重定向到链接Click Here,则转到该链接。
var count = 10;
var counter;
function start(){
counter = setInterval(timer, 1000);
}
function timer() {
var output = document.getElementById("displaySeconds");
output.innerHTML = count;
count--;
if (count < 0) {
clearInterval(counter);
window.open("https://www.google.com");
return;
}
}
window.addEventListener("load", start, false);
<br>You will redirect in <span id="displaySeconds">10</span> seconds.<br />
答案 0 :(得分:1)
如果未将div
属性设置为none(display
)来重定向用户,则可以使用文本创建单独的display: none
。计时器到期后,您可以隐藏原始文本并显示备用版本。
下面有一个有效的jsfiddle。我将计数器修改为4秒,以免等待太久,您可以根据需要进行调整。
var count = 4;
var counter;
function start() {
counter = setInterval(timer, 1000);
}
function timer() {
var output = document.getElementById("displaySeconds");
output.innerHTML = count;
count--;
if (count < 0) {
clearInterval(counter);
window.open("https://www.google.com");
let originalText = document.getElementById("original");
let noRedirectText = document.getElementById("noredirect");
originalText.style.display = "none";
noRedirectText.style.display = "block";
}
}
window.addEventListener("load", start, false);
<div>
<div id="original">
You will be redirected in <span id="displaySeconds">4</span> seconds.
</div>
<div style="display: none" id="noredirect">
If you are not redirected click <a href="https://www.google.com">here</a> to go to the link.
</div>
</div>
干杯!
答案 1 :(得分:0)
只需在间隔函数中添加代码即可隐藏第一条消息并显示另一条消息。
var count = 5;
var output = document.getElementById("displaySeconds");
var counter = null;
function timer() {
output.textContent = count;
count--;
if (count < 0) {
clearInterval(counter);
window.open("https://www.google.com");
// Hide the first message and show the second:
document.querySelector(".redirect1").classList.add("hidden");
document.querySelector(".redirect2").classList.remove("hidden");
}
}
addEventListener("load", function(){
couner = setInterval(timer, 1000);
});
.hidden { display:none; }
<div class="redirect1">You will redirect in <span id="displaySeconds">5</span> seconds.</div>
<!-- The following is initially hidden because of the CSS class -->
<div class="redirect2 hidden">If you aren't redirected, click <a href="#">here</a></div>
答案 2 :(得分:0)
如果无法进行重定向,此功能将当前文本替换为所需的文本。
var count = 10;
var counter = setInterval(timer, 1000);
var output = document.getElementById("displaySeconds");
var container = document.getElementById("container");
function timer() {
count--;
if (count === 0) {
stopTimer();
}
output.innerHTML = count;
};
function stopTimer() {
clearInterval(counter);
window.open("https://www.google.com");
container.innerHTML = ' If you are not redirected to the link <a href="https://www.google.com">Click Here</a> to go to the link.';
}
<div id="container">
You will redirect in <span id="displaySeconds">10</span> seconds.
</div>