使用onclick滚动并打开Div

时间:2015-08-12 09:55:37

标签: javascript jquery html

我有这段代码:

<a onclick="$('a[href=\'#tab-customtab\']').trigger('click');">Enquire Now</a>

<div id="tab-customtab"></div>

这会打开div #tab-customtab,但不会滚动到它。有没有办法滚动到div onclick?

2 个答案:

答案 0 :(得分:0)

这样的事情?

function scrollToId(aid){
    var aTag = $("div[id='"+ aid +"']");
    $('html,body').animate({scrollTop: aTag.offset().top},'slow');
}

来源:https://stackoverflow.com/a/8579673/4356678

答案 1 :(得分:0)

试试这个,它会让你更可靠,更有活力。

&#13;
&#13;
$(document).ready(function() {
			$(".menu").on("click",function(event) {
				
			if ($(".toggleMenu").hasClass('active')) {
			
				$(".toggleMenu").click();
			}
			$('html,body').animate({ 
			scrollTop: $(this.hash).offset().top}, 500);
			
			});
            
			$(".chosen-select").chosen();
	        
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<header>
  <nav>
    <ul>
        <li> <a href="#div1" class="menu">First</a></li>
        
        <li> <a href="#div2" class="menu">Second</a></li>
        
        <li> <a href="#div3" class="menu">Third</a></li>
        
        <li> <a href="#div4" class="menu">Forth</a></li>
    </ul>
  </nav>
</header>

<section style="height:150px;width:100%;" id="div1">
    <h2 style="text-center">First Div</h2>    
</section>

<section style="height:150px;width:100%;" id="div2">
    <h2 style="text-center">Second Div</h2>
</section>

<section style="height:150px;width:100%;" id="div3">
    <h2 style="text-center">Third Div</h2>
</section>

<section style="height:150px;width:100%;" id="div4">
    <h2 style="text-center">Forth Div</h2>
</section>
&#13;
&#13;
&#13;