2016-06-14 3 views
0

Я новичок в JavaScript. Извините, если это дубликат, но я не смог найти решение для моих нужд.Как исправить посадочную метку в неправильном положении

При нажатии на якорный тэг он ведет в желаемое положение. Однако у меня есть еще один тег привязки, который предназначен для ссылки на ту же позицию, что и на другой. Если я нажму на это (после того, как я уже нажал на другой тег привязки, который ведет к тому же положению, что и тот, который я сейчас кликнул), он НЕ приводит меня к моей желаемой позиции.

Я понимаю, это потому, что я использую hashchange. Я пробовал использовать click, но возвращает 0 для console.log(document.URL.indexOf(“#”)); вместо 58 при использовании hashchange.

Я полагаю, что логика click находится на правильном пути, но я не понимаю, почему она не делает то, что я ожидаю. (Это: клик запускается после того, как вы щелкнули что-то кликаемое на странице).

Я также пробовал использовать setTimeout, но я не мог понять, как правильно его манипулировать, чтобы «перезапустить» мою функцию fixedAnchor.

function fixedAnchor() { 
     // if (location.hash.length !== 0) { 
      window.scrollTo(window.scrollX, window.scrollY - 130); 
      console.log(document.URL.indexOf("#")); 
      // console.log(document.URL.indexOf("#") > -1 & document.URL.indexOf("#") <= 58); 
      // if (document.URL.indexOf("#") > -1 & document.URL.indexOf("#") < 58) { 
      // console.log(document.URL.indexOf("#") > -1); 
       offSetAnchor(); 
      // } 
     // } 
    } 

    function offSetAnchor() { 
     if (document.URL.indexOf("#") != 58){ 
      window.scrollTo(window.scrollX, window.scrollY - 130); 
     } 
     // setTimeout(function(){ 
     // window.scrollTo(window.scrollX, window.scrollY - 130); 
     // // fixedAnchor(); 
     // }, 1000); 
    } 

    window.addEventListener('hashchange', fixedAnchor); 
    // window.addEventListener('click', fixedAnchor); 
+0

Можете ли вы настроить JSFiddle или фрагмент здесь, чтобы показать нам всю страницу с HTML и все? –

ответ

0

Это большая польза для обработчика событий .click() JQuery в. Вы можете создать класс привязки для элементов привязки и связать событие .click().

$(".anchor").click(function(){ 
    window.scrollTo(0, 130) 
}) 

Адрес a working example.

Вы можете сделать что-то подобное без jQuery с addEventListener('onClick').

1

Это можно сделать с помощью именных якорей, используя только HTML. Пожалуйста, найдите код ниже, в котором 2 ссылки берутся в такое же положение

<!DOCTYPE html> 
<html> 

    <head> 
    <link rel="stylesheet" href="style.css"> 
    <script src="script.js"></script> 
    </head> 

    <body> 
    <a href="#gohere">click 1 to gohere</a> 
    <p>Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).</p> 
    <p><a href="#gohere">click 1 to gohere</a>Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).</p> 
    <p>Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).</p> 
    <p>Why do we use it? It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).</p> 
    <p id="gohere"> Selected Why do we use it? 
It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). 

</p> 
    </body> 

</html> 
Смежные вопросы