简体   繁体   English

单击按钮时如何自动滚动到div?

[英]How can I scroll to the div automatically when I click the button?

I Have a button at the top, 4 tables in the middle and a div (id="MasterDiv") on the bottom of a page. 我在页面顶部有一个按钮,在中间有4个表,在页面底部有一个div(id =“ MasterDiv”)。 How can I scroll to the div automatically when I click the button? 单击按钮时如何自动滚动到div? Thanks 谢谢

You can use this function (which uses jQuery's .animate ) 您可以使用此函数(使用jQuery的.animate

function scrollToElement(selector, callback){
    var animation = {scrollTop: $(selector).offset().top};
    $('html,body').animate(animation, 'slow', 'swing', function() {
        if (typeof callback == 'function') {
            callback();
        }
        callback = null;
    });
}

You call it like this: 您这样称呼它:

scrollToElement('#MasterDiv');

Or if you want to include a callback: 或者,如果您要包含回调:

scrollToElement('#MasterDiv', function(){
  alert('Page scrolled');
});
Example
A named anchor inside an HTML document:

<a name="tips">Useful Tips Section</a>
Create a link to the "Useful Tips Section" inside the same document:

<a href="#tips">Visit the Useful Tips Section</a>
Or, create a link to the "Useful Tips Section" from another page:

<a href="http://www.w3schools.com/html_links.htm#tips">
Visit the Useful Tips Section</a>

source 资源

您可以尝试以下库: http : //demos.flesler.com/jquery/scrollTo/

No animation basic Javascript Example (use ID instead of the name attribute) 没有动画基本的Javascript示例(使用ID代替name属性)

window.location = "#MasterDiv";

More on window.location 有关window.location的更多信息

Jquery Animation Example jQuery动画示例

$.scrollTo("#MasterDiv");

ScrollTo Jquery Plugin ScrollTo Jquery插件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 单击AngularJS按钮时如何滚动 - How to scroll when I click on an AngularJS button 单击按钮时如何淡入div? - How to fade in a div when I click a button? 单击按钮时如何显示div - How to show a div when I click on a button 添加新的div后,如何使JQuery UI对话框自动滚动? - How can I make a JQuery UI Dialog automatically scroll when new div is appended? 当计时器倒数至“ 0”时,如何自动“单击”按钮? (如何调用代码中的按钮?) - How can I automatically “click” a button when a timer counts down to “0”? (How do I call click on a button from code?) 当我点击按钮时 Vue JS 我希望 div 滚动到 div 的底部 - Vue JS when I click on button I want that the div scroll to bottom of the div 如何在div加载时将此click事件函数转换为自动调用的事件? - How can I turn this click event function into one that is called automatically when the div loads? 如何在点击时让 div 滚动到页面顶部? - How can I make a div scroll to the top of the page on click? 当用户单击按钮时,如何使其自动在文本字段中输入特定的关键字? - How can I make it automatically input particular keyword into text field when a user click a button? 如何在页面加载时自动点击Chrome扩展程序? - How can I make a Chrome extension automatically click a button when a page loads?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM