简体   繁体   English

单击按钮滚动到一个类-HTML

[英]Scroll to a class on button click - HTML

I have a HTML page with a frame having lot of lines and a button "Next". 我有一个HTML页面,该页面的框架包含很多行,并带有一个“下一步”按钮。 On clicking Next Button, I should be able to navigate to a paragraph having orange color. 在单击“下一步”按钮时,我应该能够导航到具有橙色的段落。 All the paragraphs having orange color will be of same class. 所有具有橙色的段落将属于同一类。

That means, on page load I should be able to navigate to 3rd paragraph. 这意味着,在页面加载时,我应该能够导航到第3段。 On another click I should go to 6th paragraph and so on.. 再次单击,我应该转到第6段,依此类推。

I tried to use document.getelementsbyclassname(). 我尝试使用document.getelementsbyclassname()。 But I was not able to write logic to navigate to that particular location. 但是我无法编写逻辑来导航到该特定位置。 Please help me out. 请帮帮我。 在此处输入图片说明

You can do this , like this 你可以这样

Working DEMO 工作演示

$("p:first").addClass("active");

$(document).on("click","#ip",function(){
    if($("p.orange:last").hasClass("active")){

           var topVal = $("p:first").offset().top;

           $("html body").animate({
                scrollTop:topVal
            },500,function(){
                $("p").removeClass("active");
                $("p:first").addClass("active");
            });
       }
    else{
        var nextElem = $("p.active").nextAll("p.orange:first");

        var topVal = nextElem.offset().top;
        //alert(topVal);
        $("html body").animate({
            scrollTop:topVal
        },500,function(){
            $("p").removeClass("active");
            nextElem.addClass("active");
        });
   }
});

You can try this. 你可以试试看 First, create a variable called, lets's say, number which stores which paragraph we currently need to scroll to. 首先,创建一个名为number的变量,该变量存储我们当前需要滚动到的段落。 Like 1st, 2nd, etc. When the page loads, it's value will be 1 . 类似于1st,2nd等。加载页面时,其值为1

var number=1;

The next step is to add ids to all the orange paragraph. 下一步是将id添加到所有橙色段落。 The first paragraph gets id orange1 , the second one gets id orange2 and so on. 第一段的ID为orange1 ,第二段的ID为orange2 ,依此类推。 You can either do this manually or if there are too many paragraphs you can try adding it by looping or something like that. 您可以手动执行此操作,或者如果段落太多,则可以尝试通过循环或类似的方式添加它。

Now assuming the Next button has an id called 'button' you can add this code: 现在,假设“ 下一步”按钮具有一个名为“按钮”的ID,您可以添加以下代码:

$('#button').click(function() {
    $('html, body').animate({
        scrollTop: $('#orange'+number).offset().top
    }, 1000);

    number++;
});

Now, whenever you click on the Next button, the page should scroll to the correct paragraph. 现在,无论何时单击“ 下一步”按钮,页面都应滚动到正确的段落。 Hope this helps. 希望这可以帮助。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM