Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

html - Scrolling to an Anchor using Transition/CSS3

I have a series of links which are using an anchor mechanism:

<div class="header">
    <p class="menu"><a href="#S1">Section1</a></p>
    <p class="menu"><a href="#S2">Section2</a></p>
    ...
</div>
<div style="width: 100%;">
<a name="S1" class="test">&nbsp;</a>
<div class="curtain">
Lots of text
</div>

<a name="S2" class="test">&nbsp;</a>
<div class="curtain">
lots of text
</div>
...
</div>

I am using the following CSS:

.test
{
    position:relative; 
    margin: 0; 
    padding: 0; 
    float: left;
    display: inline-block;
    margin-top: -100px; /* whatever offset this needs to be */
}

It's working fine. But of course, it's jumping from one section to the next when we click on the link. So I'd like to have a smooth transition, using a scroll of some sort to the start of selected section.

I think I read on Stackoverflow that this is not possible (yet) with CSS3 but I'd like a confirmation and also I'd like to know what 'could' be the solution. I am happy to use JS but I can't use jQuery. I tried to use an on click function on the link, retrieve the "vertical position" of the div that needs to be displayed but I was unsuccessful. I am still learning JS and don't know it well enough to come up with a solution of my own.

Any help/ideas would be greatly appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use the scroll-behavior CSS property (which is supported in all browsers except Internet Explorer and Safari):

a {
  display: inline-block;
  padding: 5px 7%;
  text-decoration: none;
}

nav, section {
  display: block;
  margin: 0 auto;
  text-align: center;
}

nav {
  width: 350px;
  padding: 5px;
}

section {
  width: 350px;
  height: 130px;
  overflow-y: scroll;
  border: 1px solid black;
  font-size: 0; 
  scroll-behavior: smooth;    /* <----- THE SECRET ---- */
}

section div{
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  font-size: 8vw;
}
<nav>
? <a href="#page-1">1</a>
? <a href="#page-2">2</a>
? <a href="#page-3">3</a>
</nav>
<section>
? <div id="page-1">1</div>
? <div id="page-2">2</div>
? <div id="page-3">3</div>
</section>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...