您当前的位置:首页 > 计算机 > 编程开发 > Html+Div+Css(前端)

几种常见的页面跳转代码

时间:10-02来源:作者:点击数:
CDSY,CDSY.XYZ

1. HTML Meta 标签跳转

<!-- 3秒后跳转到指定页面 -->
<meta http-equiv="refresh" content="3;url=https://www.example.com">

<!-- 立即跳转 -->
<meta http-equiv="refresh" content="0;url=https://www.example.com">

2. JavaScript 跳转

<script>
// 立即跳转
window.location.href = "https://www.example.com";

// 延迟跳转(3秒后)
setTimeout(function() {
    window.location.href = "https://www.example.com";
}, 3000);

// 替换当前历史记录
window.location.replace("https://www.example.com");
</script>

3. JavaScript 函数封装

<script>
function redirectTo(url, delay = 0) {
    if (delay > 0) {
        setTimeout(function() {
            window.location.href = url;
        }, delay);
    } else {
        window.location.href = url;
    }
}

// 使用示例
redirectTo("https://www.example.com", 2000); // 2秒后跳转
</script>

4. 链接点击跳转

<!-- 普通链接 -->
<a href="https://www.example.com">点击跳转</a>

<!-- 带确认的跳转 -->
<a href="https://www.example.com" onclick="return confirm('确定要跳转吗?')">确认跳转</a>

<!-- 按钮跳转 -->
<button onclick="window.location.href='https://www.example.com'">跳转</button>

5. 条件跳转

<script>
// 根据条件跳转
if (someCondition) {
    window.location.href = "page1.html";
} else {
    window.location.href = "page2.html";
}

// 根据用户代理跳转
if (/Mobile|Android|iPhone/i.test(navigator.userAgent)) {
    window.location.href = "mobile.html";
} else {
    window.location.href = "desktop.html";
}
</script>

6. 带参数的跳转

<script>
function redirectWithParams(baseUrl, params) {
    const url = new URL(baseUrl);
    Object.keys(params).forEach(key => {
        url.searchParams.set(key, params[key]);
    });
    window.location.href = url.toString();
}

// 使用示例
redirectWithParams("https://www.example.com", {
    "id": 123,
    "type": "user",
    "source": "redirect"
});
</script>

7. 在新窗口打开

<script>
// 新窗口打开
window.open("https://www.example.com", "_blank");

// 带参数的新窗口
window.open("https://www.example.com", "_blank", "width=800,height=600");
</script>

8. 完整的页面跳转示例

<!DOCTYPE html>
<html>
<head>
    <title>跳转页面</title>
    <script>
        // 页面加载后5秒跳转
        window.onload = function() {
            setTimeout(function() {
                document.getElementById('countdown').innerHTML = '正在跳转...';
                window.location.href = 'https://www.example.com';
            }, 5000);
        };
        
        // 倒计时显示
        let count = 5;
        setInterval(function() {
            if (count > 0) {
                document.getElementById('countdown').innerHTML = 
                    count + '秒后自动跳转...';
                count--;
            }
        }, 1000);
    </script>
</head>
<body>
    <div id="countdown">5秒后自动跳转...</div>
    <a href="https://www.example.com">立即跳转</a>
</body>
</html>

选择适合你需求的跳转方式,注意考虑用户体验和SEO影响。

CDSY,CDSY.XYZ
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐