2016-07-09 8 views
-1

Ich habe diese Funktion, die ich online gefunden, dass die href in Meine Tags verursacht gescrollt werden, anstatt es erscheinen nur:Anruffunktion für HTML <a> Tags entworfen von Javascript

$(function() { 
    var headerHeight = 70; 
    $('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 - headerHeight 
       }, 1000); 
       return false; 
      } 
     } 
    }); 
}); 

Jetzt muss ich bekommen eine Stelle in der Seite von JavaScript-Code verwenden, weil ich eine peinliche Situation, wo die Form-Taste auch zu einem Ort bewegen vorlegen soll:

 <div 
      value="GO" 
      id="go-div" 
      class="bubble"> 

      <input type="submit" 
        value="GO" 
        id="go-button" 
        style=" position: absolute; 
           width: 100%; 
           height: 100%; 
           top: 0; 
           left: 0;" 

       onclick="location.href='#search-results-page';"> 
      </input> 
     </div> 

wie ändere ich die location.href='#search-results-page'; die Scroll-Funktion zu benutzen?

Antwort

2

Mehrere Möglichkeiten, das zu tun. Hier ein Beispiel: https://jsfiddle.net/nx7xf1nb/

$(function() { 
    var headerHeight = 70; 
    $('a[href*="#"]:not([href="#"])').click(function() { 
     if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) { 
      if (gotoTarget(this.hash)) 
       return false; 
     } 
    }); 

    $('input[data-target]').click(function() { 
     if (gotoTarget($(this).data("target"))) 
      return false; 
    }) 

    function gotoTarget(targetName) { 
     var target = $(targetName); 
     target = target.length ? target : $('[name="' + targetName.slice(1) + '"]'); 
     if (target.length) { 
      $('html,body').animate({ 
       scrollTop: target.offset().top - headerHeight 
      }, 1000); 

      return true; 
     } 

     return false; 
    } 
}); 

Button:

<input style="position: absolute; width: 100%; height: 100%; top: 0; left: 0;" 
     type="submit" 
     data-target="#search-results-page" 
     value="GO" 
     id="go-button"> 
+0

Ich denke, dass es eine sehr elegante Lösung ist in der Lage sein, einfach ein Datenzielattribut auf Elemente hinzufügen, die zu einer Stelle bewegen müssen, wenn geklickt. +1! Vielen Dank. – BeniaminoBaggins