jQuery scroll to anchor (minus set amount of pixels)

半世苍凉 提交于 2019-11-29 23:54:00

I just had to solve this problem myself. You need to adjust your offset by the amount of pixels you want to scrollTo. In my case, I needed it to be 50 pixels higher on the page. So, I subtracted 50 from targetOffset.

Now, the part of the code that's throwing a wobbly for you is location.hash - this is telling the browser to set its location to a specific point. In all cases, this is a string containing the ID you just scrolled to. So, it'd be something like '#foo'. You need to maintain this, so we'll leave it.

However, to prevent the browser from 'jumping' when location.hash is set (a default browser action), you simply need to prevent the default action. So, pass your event 'e' through the completion function in the animate function. Then simply call e.preventDefault(). You'll have to make sure that the browser is actually calling an event, otherwise it will error out. So, an if-test fixes that.

Done. Here's the revised code chunk:

if (target) {
    var targetOffset = $target.offset().top - 50;
    $(this).click(function(event) {
      if(event != 'undefined') {
          event.preventDefault();}
      $(scrollElem).animate({scrollTop: targetOffset}, 400, function(e) {
          e.preventDefault();
          location.hash = target;
      });
    });
  }

This is what I use:

function scrollToDiv(element){
    element = element.replace("link", "");
    $('html,body').unbind().animate({scrollTop: $(element).offset().top-50},'slow');
};

...where 50 is the number of pixels to add/subtract.

This code work for me in any link anchor in my site respect "150px" height for fix menu on top.

<!-- SMOOTH SCROLL -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top-150
        }, 1000);
        return false;
      }
    }
  });
});
</script>
<!-- End of SMOOTH SCROLL -->

Lol)

<span class="anchor" id="section1"></span>
<div class="section"></div>

<span class="anchor" id="section2"></span>
<div class="section"></div>

<span class="anchor" id="section3"></span>
<div class="section"></div>

<style>
.anchor{
  display: block;
  height: 115px; /*same height as header*/
  margin-top: -115px; /*same height as header*/
  visibility: hidden;
}
</style>

I was unable to use Jonathan Savage's solution as I couldn't pass an event callback into animate() without error. I had this issue today and found a simple solution:

      var $target = $(this.hash), target = this.hash;
      if (target) {
        var targetOffset = $target.offset().top - 92;
        $(this).click(function(event) {
          event.preventDefault();
          $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
            location.hash = targetOffset;
          });
        });

Subtract your pixel offset from the targetOffset variable, then assign location.hash to that variable. Stops the page jumping when scrolling to the target hash.

This is a jQuery snippet i use and find very resourceful & flexible. You can remove the DOM Ready if you run it in the footer which is suggested. Just load any post 1.4v library ahead of it. It listens for all clicks on anchors, then it runs a boolean and an OR for class checks. If it finds a class then it runs through the script and animation. You can adjust your offset from its ending position i prefer 60px on most applications but feel free to adjust as need be.

<!--jQuerySmoothScroll-->
<script>
jQuery(document).ready(function(){
  	// Add smooth scrolling to all links
  	jQuery("a").on('click', function(event) {
      //check that we have the smooth-scroll class add as many as need be
            if (jQuery(this).hasClass("whatever-class-you-want") || jQuery(this).hasClass("smooth-scroll")) {
    			// Make sure this.hash has a value before overriding default behavior
   		 			if (this.hash !== "") {
      					// Prevent default anchor click behavior
      				event.preventDefault();
      			// Store hash
      			var hash = this.hash;
     	 	// Using jQuery's animate() method to add smooth page scroll
      		// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
        jQuery('html, body').animate({
        scrollTop: jQuery(hash).offset().top-60// Set offset from top position
       }, 800, function(){
   
        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
     } // End if
    } // End if (class)
  });
});
</script>

This is a jQuery implementation which I use that was based on Никита Андрейчук's solution. The pixel adjustment variable can be set dynamically this way, though it is hard coded in this example.

$( 'a' ).each(function() {
    var pixels = 145;
    var name = $( this ).attr( 'name' );
    if ( typeof name != 'undefined' ) {
        $( this ).css({
          'display'    : 'block',
          'height'     : pixels + 'px',
          'margin-top' : '-' + pixels + 'px',
          'visibility' : 'hidden'
        });
    }
});

Here is what i use. Set the offset to what you need.

$('a[href^="#"]').click(function(e) {
  e.preventDefault();
  $(window).stop(true).scrollTo(this.hash {duration:1000,interrupt:true,offset: -50});
});

Not wanting to learn Javascript and always looking for the easiest option, just create an empty DIV above the anchor point you want to land at then in CSS make the div

anchorpointl{margin-top: -115px;}

or however far above or below you want to go and the jobs done

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!