1

Quando clico na âncora e rolo a página acontece um conflito entre o script de rolagem suave e o de âncora fazendo com que o site role para o topo, já tentei de todo jeito resolver isso e não consigo de forma alguma, se alguém puder me ajudar ficarei extremamente grato

SITE: https://circuito-da-saude.herokuapp.com/web

SCRIPT SMOOTH SCROLLBAR:

function smooth(){
    new WSmoothScroll(document,120,12);
}
 
// var isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
 
function WSmoothScroll(target, speed, smooth) {
    if (target == document)
        target = (document.documentElement || document.body.parentNode || document.body) // cross browser support for document scrolling
    var moving = false
    var pos = target.scrollTop
    if(navigator.userAgent.indexOf("Firefox") > -1) {
        target.addEventListener('DOMMouseScroll', scrolled, {passive: false});
    } else {
        if(navigator.userAgent.indexOf('Safari') != -1 && navigator.userAgent.indexOf('Chrome') == -1) {
           
        } else {
            target.addEventListener("wheel", scrolled, {passive: false} );
        }
    }
 
    function scrolled(e) {
        e.preventDefault(); // disable default scrolling
 
        var delta = normalizeWheelDelta(e)
 
        pos += -delta * speed
        pos = Math.max(0, Math.min(pos, target.scrollHeight - target.clientHeight)) // limit scrolling
 
        if (!moving) update()
    }
 
    function normalizeWheelDelta(e){
        if(e.detail){
            if(e.wheelDelta)
                return e.wheelDelta/e.detail/40 * (e.detail>0 ? 1 : -1) // Opera
            else
                return -e.detail/8 // Firefox 3
        }else
            return e.wheelDelta/360 // IE,Safari,Chrome 120
    }
 
    function update() {
        moving = true
        var delta = (pos - target.scrollTop) / smooth
        target.scrollTop += delta
        if (Math.abs(delta) > 0.5)
            requestFrame(update)
        else
            moving = false
    }
 
    var requestFrame = function() { // requestAnimationFrame cross browser
        return (
            window.requestAnimationFrame ||
            window.webkitRequestAnimationFrame ||
            window.mozRequestAnimationFrame ||
            window.oRequestAnimationFrame ||
            window.msRequestAnimationFrame ||
            function(func) {
                window.setTimeout(func, 1000 / 50); // 1000 / 50
            }
        );
    }()
}

SCRIPT ÂNCORA:

var links = document.getElementsByClassName('scroll-link');
 
for (var k = 0; k < links.length; k++) {
    links[k].onclick = scroll;
}
 
function scroll(e) {
    e.preventDefault();
    var id = this.getAttribute('href').replace('#', '');
    var target = document.getElementById(id).getBoundingClientRect().top;
    animateScroll(target);
 
    // recolhe menu após smoothScroll
 
    if(document.querySelector('.sandwich-trigger').classList.contains('sandwich-open') == true) {
        document.querySelector('.menu ul').classList.remove('nav-open');
        document.querySelector('.sandwich-trigger').classList.remove('sandwich-open');
    }
 
}
 
function animateScroll(targetHeight) {
    targetHeight = document.body.scrollHeight - window.innerHeight > targetHeight + scrollY ?
        targetHeight : document.body.scrollHeight - window.innerHeight;
    var initialPosition = window.scrollY;
    var SCROLL_DURATION = 40;
    var step_x = Math.PI / SCROLL_DURATION;
    var step_count = 0;
    requestAnimationFrame(step);
    function step() {
        if (step_count < SCROLL_DURATION) {
            requestAnimationFrame(step);
            step_count++;
            window.scrollTo(0, initialPosition + (targetHeight - 70) * 0.25 * Math.pow((1 - Math.cos(step_x * step_count)), 2));
        }
    }
}

2 Respostas 2

3

Vou te dar um work around. Hoje é possível fazer ancoras suaves apenas com CSS usando o scroll-behavior, então vc não precisa necessariamente usar um Script para a Ancora Suave, usa o CSS para isso, assim eliminando um dos Scripts e prevenindo esse conflito.

Aqui vc pode ler sobre o scroll-behavior https://developer.mozilla.org/pt-BR/docs/Web/CSS/scroll-behavior

Suporte dos Browsers: https://caniuse.com/#feat=css-scroll-behavior

Segue um exemplo prático de rolagem suave só com CSS, não tem JS aqui.

html {
    overflow-y: scroll;
    scroll-behavior: smooth;
}     
body {
	background-image: linear-gradient(to bottom, #00f 0%, #000 100%);
}     
html, body {
  width: 100%;
  height: 100%;
  margin: 0;
  padding: 0;
}
a {
	font-size: 40px;
	color: #fff;
}
#ancoragem {
	height: 100px;
	background-color: red;
	margin-top: 150vh;
    display:block;
    position:relative;
}
<a href="#ancoragem" id="ancora">ancora</a>

<a href="#ancora" id="ancoragem">VOLTAR PRO TOPO!</a>

2
  • Olá muito obrigado por disponibilizar seu tempo, a questão da âncora com css é o suporte que ainda é limitado e o público alvo do site é composto por pessoas leigas que usam browsers mais antigos, por isso preciso de uma solução em js que seja crossbrowser
    – Renan Hugo
    30/04/2019 às 17:42
  • @RenanHugo sim ainda é algo com pouco suporte, é mais um paliativo caso vc não consiga alguma resposta mais precisa.
    – hugocsl
    30/04/2019 às 17:46
0

essa linha (linha 9 do script de scroll) transforma a variavel target em um valor boolean target = (document.documentElement || document.body.parentNode || document.body) sendo assim na linha 11 target.scrollTop retorna undefined o que causa o comportamento

1
  • Olá Guilherme, comentei essa linha mas o código parou de funcionar... Qual seria a sugestão para sanar esse problema?
    – Renan Hugo
    30/04/2019 às 19:39

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .