如何在 CSS 中滚动到特定元素或跳过内容?
在访问某些网站时,用户可能需要跳过不相关的内容,直接跳转到自己感兴趣的内容,并且在 CSS 中有很多方法可以做到这一点。用户可能希望点击一个按钮或链接,将他们带到同一页面上的某个元素。用户可能希望滚动到特定元素或能够跳过内容。
在本文中,我们将了解如何在 CSS 中滚动到特定元素或跳过特定内容。
如何滚动到元素或内容?
有多种方法可以跳过内容,例如,我们可以使用 scroll-behaviour 属性并将其值设置为 smooth,以便向上滚动可以平滑进行,但是使用此属性不会让我们对滚动有太多控制权,因为它只会使滚动平滑。我们可以像这样使用 scroll-behaviour 属性:
html{
scroll-behaviour: smooth;
}
我们还可以使用另一种方法,在这两种方法中,我们都没有关注特定元素,它们只是向上滚动。
<html>
<body>
<a id="to the top"> </a>
<a href="#top"> This will take you to the top of the page</a>
</body>
</html>
以上示例将带您到页面顶部,而不是特定元素。要跳到特定元素并跳过内容,让我们看一个示例
示例
我们将要采用的方法是定位内容并创建一个容器,其中包含我们所有链接,并在 section 部分使用锚点标签并为它们提供 id,以便锚点标签可以指向它们。让我们看看代码
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example for scrolling to an element</title>
<style>
.scroll-to {
position: absolute;
top: 1200px;
}
.scroll-btn {
position: fixed;
bottom: 20px;
right: 20px;
padding: 10px 20px;
background-color: blue;
color: white;
text-decoration: none;
cursor: pointer;
}
</style>
</head>
<body>
<div id="content">
<h1>Page Content</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed auctor, metus in facilisis pellentesque, nulla orci tristique dolor, euismod malesuada augue massa ac dolor.</p>
<div class="scroll-to">
<h2>Scroll to me!</h2>
</div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed auctor, metus in facilisis pellentesque, nulla orci tristique dolor, euismod malesuada augue massa ac dolor.</p>
</div>
<a href="#" class="scroll-btn" onclick="scrollToTarget()">Scroll</a>
<script>
function scrollToTarget() {
var target = document.querySelector('.scroll-to');
target.scrollIntoView({behavior: 'smooth'});
}
</script>
</body>
</html>
在上面给出的代码的输出中,将有一个标题“页面内容”和在标题下编写的文字内容,并且屏幕右下角会有一个写着“滚动”的按钮>您需要滚动到页面底部,在那里您将看到标题“滚动到我” 当您按下“滚动”按钮时,页面将自动将您带到“页面内容”。
示例
我们将要采用的方法是定位内容并创建一个容器,其中包含我们所有链接,并在 section 部分使用锚点标签并为它们提供 id,以便锚点标签可以指向它们。让我们看看代码
<!DOCTYPE html>
<html lang="en">
<head>
<title>Example of scrolling to a particular element </title>
<style>
.con{
justify-content: space-between;
display: flex;
}
section:target {
border: solid blue 1px;
}
</style>
</head>
<body>
<div class="con">
<a href="#section1">Go to The Section 1</a>
<a href="#section2">Go to The Section 2</a>
</div>
<section id="section1">
<h2>This is Section 1</h2>
</section>
<section id="section2">
<h2>This is Section 2</h2>
</section>
</body>
</html>
在输出中,您可以看到有两个超链接,无论单击其中的哪一个,该特定部分都会显示蓝色边框,表明单击超链接将把用户带到所需的元素。
结论
当用户想要跳过与自己无关的内容时,他/她可能希望直接跳转到自己感兴趣的内容。使用锚点标签并将它们指向特定部分的 id 向我们展示了如何滚动到特定元素。
在本文中,我们了解了如何使用 CSS 属性滚动到特定元素或跳过内容。
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP