一定时间后重定向网站


135

要在网站上显示某个功能,该功能会在3秒左右的时间内将您重定向到该网站,我该怎么办?



我很好奇,为什么你要这么做呢?每当我访问这样的页面时,我宁愿在0秒内得到指导。
allesklar 2010年

@allesklar对不起您的答复。我正在开发一个网站,我想看看是否可以轻松地从代码编辑器切换到Web浏览器,而不必每次都刷新。
codedude

JS重定向生成器将帮助您轻松创建延迟的重定向代码段。它具有noscript和seo支持,并且具有IE 8(及更低版本)的修复程序,可传递http引用!
PatarticsMilán2015年

1
@allesklar一个使用此示例。如果您更改域,并希望每个人都在第一个月内重定向到新域(但要让他们知道一个月后会删除旧域)。因为即使您发送和发送电子邮件,总会有人忘记并转到旧域。
patricia '02

Answers:



69

您可能正在寻找meta refresh标签

<html>
    <head>
        <meta http-equiv="refresh" content="3;url=http://www.somewhere.com/" />
    </head>
    <body>
        <h1>Redirecting in 3 seconds...</h1>
    </body>
</html>

请注意,meta refresh如今已经不赞成使用和禁止使用,但是有时它是唯一可行的选择(例如,如果您无法在服务器端生成HTTP重定向标头和/或需要支持非JavaScript客户端等)。


52

如果您希望获得更大的控制权,则可以使用javascript而不是使用meta标签。这将使您具有某种视觉效果,例如倒数计时。

这是使用一个非常基本的方法 setTimeout()

<html>
    <body>
    <p>You will be redirected in 3 seconds</p>
    <script>
        var timer = setTimeout(function() {
            window.location='http://example.com'
        }, 3000);
    </script>
</body>
</html>


如果您希望文本在重定向之前动态递减为0,则可以采用这种方法。使用1秒计时器,其中计时器功能更新HTML文本,然后启动新的1秒计时器,直到3秒钟过去,然后执行重定向。
雷米·勒博

19

这是一个X秒钟后重定向(更新计数器div)的完整(但很简单)示例:

<html>
<body>
    <div id="counter">5</div>
    <script>
        setInterval(function() {
            var div = document.querySelector("#counter");
            var count = div.textContent * 1 - 1;
            div.textContent = count;
            if (count <= 0) {
                window.location.replace("https://example.com");
            }
        }, 1000);
    </script>
</body>
</html>

counterdiv 的初始内容是等待的秒数。


这并没有工作,直到我取代location.href="https://example.com";window.location='https://example.com'
NateH06

1
window.location.replace("http://example.com");出于此处讨论的原因,可能会更好使用:stackoverflow.com/a/506004所做的更改将使此答案更为通用。
赛西

10

最简单的方法是使用HTML META标签,如下所示:

<meta http-equiv="refresh" content="3;url=http://example.com/" />

维基百科


4

将以下HTML重定向代码放在HTML代码的和标记之间。

<meta HTTP-EQUIV="REFRESH" content="3; url=http://www.yourdomain.com/index.html">

上面的HTML重定向代码会将您的访问者立即重定向到另一个网页。content =“ 3;可能会更改为您希望浏览器在重定向之前等待的秒数,例如4、5、8、10或15秒等。


1

使用此简单的JavaScript代码使用特定的时间间隔将页面重定向到另一页面...

请将此代码添加到您要重定向的网站页面:

<script type="text/javascript">
(function(){
   setTimeout(function(){
     window.location="http://brightwaay.com/";
   },3000); /* 1000 = 1 second*/
})();
</script>

<meta http-equiv="refresh" content="3;url=http://example.com/" />是一个更好的选择,因为它更简单并且无需JavaScript支持即可工作。
爱德华

您是对的兄弟...但这取决于情况。.有时候我们需要重定向特定事件,因为JS是最好的选择。
Sunny SM

我明白您的意思,“ Sunny SM”。尽管应该几乎总是使用meta标签,但是在像您这样的特定场景中,JavaScript是唯一的选择。
爱德华
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.