Skip to content

锚点的添加 #47

Open
Open
@funnycoderstar

Description

@funnycoderstar

锚点的添加

1.使用 id 定位

这种定位最大的好处就是可以针对任何标签来定位
给一个a标签一个href=“#锚点”,然后要跳的锚点给个id=“锚点”

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>锚点</title>
    <style>
        #div1 {
            margin-top: 2000px;
        }
    </style>
</head>
<body>
    <h2>
        <a href="#div1">to div1</a>
    </h2>
    <div id="div1">div1</div>
</body>
</html>

2.使用 name 定位

使用 name 定位只用于 <a>标签,其他的标签就不管用了。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>锚点</title>
    <style>
        a[name="a"]{
            margin-top: 2000px;
            display: block;
        }
    </style>
</head>
<body>
    <h2>
        <a href="#a">定位到A</a>
    </h2>
    <a name="a">A</a> 
</body>
</html>

3.使用js定位

element.scrollIntoView()方法让当前元素滚动到浏览器窗口的可视区域内(有浏览器的兼容问题)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>锚点</title>
    <style>
        #a {
            margin-top: 2000px;
        }
    </style>
</head>
<body>
    <div onclick="javascript:document.getElementById('a').scrollIntoView()">
        定位到A
    </div>
    <div id="a">
        A
    </div>
</body>
</html>

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions