Использование изображений в качестве кликабельных якорных ссылок - PullRequest
0 голосов
/ 08 января 2019

У меня есть sidenav, составленный из нескольких изображений. Я хочу, чтобы эти изображения были ссылками на разделы на одной странице - якорные ссылки. Тем не менее, я не могу заставить его работать.

Вот мой HTML:

<div id="nav2"><a href="#powerlifting"><img src="img/icon1.png" alt=""></a></div>

<a name="powerlifting"></a>
<div id="powerlifting">
    <div class="header1"><h1>POWERLIFTING</h1></div>
</div>

Вот стиль на # nav2:

#nav2 {
    position: fixed;
    top: 14.285vh;
    cursor: pointer;
}

Заранее спасибо! : -)

Ответы [ 3 ]

0 голосов
/ 08 января 2019

position: fixed или sticky в макете

Ваш макет для изображения и ссылки находится на и при нормальных обстоятельствах у вас не должно быть проблем. Таким образом, мы можем, вероятно, предположить, что окружающий макет, созданный вокруг фиксированной навигационной панели, наносит вред стандартному поведению перехода на якорь <a>. Вместо того, чтобы ждать больше вашего кода (что - без обид - вероятно, ужасный беспорядок), я сделал полностью функциональное решение HTML / CSS для проблем, которые у вас, вероятно, возникнут, когда вы заработаете простой якорь.


Демо

При просмотре этого deno, нажмите ссылку Полная страница. Он не выглядит так здорово в кадре, который имеет нестандартные размеры, потому что большая часть длины демонстрации связана с областью просмотра.

enter image description here

<!DOCTYPE html>
<html>

<head>
  <meta charset='utf-8'>
  <title></title>
  <link href="https://fonts.googleapis.com/css?family=Rye" rel="stylesheet">
  <style>
    /* Basic reset */
    
    * {
      margin: 0;
      padding: 0;
    }
    /* vh and vw units will be used throughout this demo */
    
    html,
    body {
      width: 100vw;
      height: 100vh;
      font: 400 oblique 6vh/1.45 Times;
      overflow: hidden;
    }
    /* Animates scrolling */
    
    body {
      margin: 0 auto;
      overflow-y: scroll;
      scroll-behavior: smooth;
    }
    
    h1 {
      font: 700 small-caps 2rem Rye;
      margin: 0.67em 0 0.67em 5vw;
    }
    
    h2 {
      font: 700 small-caps 1.5rem Rye;
      margin: 0.83em 0;
    }
    
    h3 {
      font: small-caps 1.25rem Rye;
      margin: 1em 0;
    }
    /* Make sure to set z-index to an integer */
    
    nav {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      z-index: 1;
      border-bottom: 2px ridge #000;
      height: 10vh;
      min-height: 50px;
      width: 100%;
      background: #ddd;
    }
    
    nav a {
      text-decoration: none;
      font-style: normal;
      max-height: 10vh;
      min-height: 50px;
      line-height: 16vh;
      vertical-align: top;
    }
    
    a img {
      height: 10vh;
      max-height: 10vh;
      min-height: 50px;
    }
    
    main {
      margin: 0 auto;
    }
    
    section {
      margin: 0 auto;
      padding: 0 5vw;
    }
    
    article {
      margin: 1rem auto 0;
    }
    
    p {
      margin: 1em 0;
    }
    /*
    Compensates for the fixed navbar height offset when jumping 
    to an anchor. https://stackoverflow.com/a/28824157/2813224
    */
    
     :target::before {
      content: "";
      display: block;
      height: 5vh;
      margin-top: -5vh;
    }
    
    .banner-logo {
      text-align: right;
      height: 70vh;
      margin-bottom: 15vh;
    }
    
    .banner-logo img {
      height: 100%;
      width: auto;
    }
  </style>
</head>

<body>
  <nav>
    <a href="#main">
      <img src="http://alexandre.roulois.fr/data/dev/rkl/icon.png" alt=""> Home
    </a>

    <a href="#sec1">
      <img src="https://img2.apk.tools/150/2/0/9/com.tao101.chucknoris.chucknorrisjokes.png" alt=""> Section 1
    </a>

    <a href="#sec2">
      <img src="https://img2.apk.tools/150/2/0/9/com.tao101.chucknoris.chucknorrisjokes.png" alt=""> Section 2
    </a>
  </nav>

  <main>
    <a id='main'>&nbsp;</a>
    <header>
      <h1>All Things Chuck</h1>
      <figure class='banner-logo'>
        <img src='https://webiconspng.com/wp-content/uploads/2017/09/Chuck-Norris-PNG-Image-50835.png'>
      </figure>
    </header>

    <section>
      <a id='sec1'>&nbsp;</a>
      <header>
        <h2>Section 1</h2>
      </header>

      <p>Chuck Norris doesn't churn butter. He roundhouse kicks the cows and the butter comes straight out Chuck Norris doesn't wash his clothes, he disembowels them, Chuck Norris doesn't wear a watch. HE decides what time it is.</p>

      <article>
        <h3>Article 1</h3>
        <p>Chuck Norris will attain statehood in 2009. His state flower will be the Magnolia, Chuck Norris doesn't wear a watch. HE decides what time it is Contrary to popular belief, America is not a democracy, it is a Chucktatorship, Chuck Norris' hand
          is the only hand that can beat a Royal Flush Chuck Norris originally appeared in the "Street Fighter II" video game, but was removed by Beta Testers because every button caused him to do a roundhouse kick. When asked bout this "glitch," Norris
          replied, "That's no glitch." When Chuck Norris roundhouse kicks you and misses it kills 75% of the population that was standing in the direct line of Chuck, But Chuck never misses The leading causes of death in the United States are: 1. Heart
          Disease 2. Chuck Norris 3. Cancer. Outer space exists because it's afraid to be on the same planet with Chuck Norris Chuck Norris is ten feet tall, weighs two-tons, breathes fire, and could eat a hammer and take a shotgun blast standing.</p>
        <p>Chuck Norris is the only man to ever defeat a brick wall in a game of tennis. When the Boogeyman goes to sleep every night, he checks his closet for Chuck Norris.</p>
      </article>

      <article>
        <h3>Article 2</h3>
        <p>Most people have 23 pairs of chromosomes. Chuck Norris has 72... and they're all poisonous. There is no theory of evolution. Just a list of creatures Chuck Norris has allowed to live. Chuck Norris likes children...they taste like chicken, Chuck
          Norris doesn't churn butter. He roundhouse kicks the cows and the butter comes straight out, After discovering the secrets to time travel, Chuck Norris secretly replaced each player on the 1972 Dolphins team, thus making them undefeated. Chuck
          Norris doesn't dress up for Halloween, he's scary enough Chuck Norris figured out the secret of the universe. He just never told anyone, When Chuck Norris does a pushup, he isn't lifting himself up, he's pushing the Earth down Chuck Norris does
          not get frostbite. Chuck Norris bites frost, Contrary to popular belief, there is one thing faster then the speed of light, Chuck Norris' foot Chuck Norris once roundhouse kicked someone so hard that his foot broke the speed of light, went back
          in time, and killed Amelia Earhart while she was flying over the Pacific Ocean.</p>
      </article>
    </section>

    <section>
      <a id='sec2'>&nbsp;</a>
      <header>
        <h2>Section 2</h2>
      </header>

      <article>
        <p>Outer space exists because it's afraid to be on the same planet with Chuck Norris, There is no theory of evolution. Just a list of animals Chuck Norris allows to live. For every action, there is an unequal and opposite reaction from Chuck Norris
          that kills you, Crop circles are Chuck Norris' way of telling the world that sometimes corn needs to lie down. Chuck Norris is currently suing NBC, claiming Law and Order are trademarked names for his left and right legs Chuck Norris is the
          reason why Waldo is hiding</p>
      </article>

    </section>
  </main>
</body>

</html>
0 голосов
/ 09 января 2019

Я разобрался с ответом на мой вопрос! Добавление значения z-index в # nav1, кажется, делает трюк

#nav2 {
    position: fixed;
    top: 14.285vh;
    cursor: pointer;
    z-index: 9999;
}
0 голосов
/ 08 января 2019

Код выше, похоже, работает. Тег привязки с href из #powerlifting фактически переходит на div#powerlifting. Возможно, вы этого не видите, потому что ваш div может быть недостаточно высоким.

Если вы хотите прокрутить анимацию вниз, вам нужно будет использовать JS или CSS.

Это может быть связанный ответ: Прокрутка до привязки с помощью Transition / CSS3 . Прилагаемая JS Fiddle (из соответствующего ответа) может быть вам полезна: http://jsfiddle.net/YYPKM/3/

...