简体   繁体   中英

When i add a div element to the page it loose focus an scroll to top

I have a link when its clicked a div containing form elements are added to the page. The problem is when the list become longer. when i add an element to the end of the page, the page focus back to the top making the user to scroll back to the end of the page. How can I prevent it? I tried to use $(this).focus(); but it didn't work.

$("a[id^=link_add_section_]").live('click',function() { // create a section

                var sectionId = $(this).attr('id');
                var sectionIdSplit = sectionId.split('_');
                addSection(sectionIdSplit[3],'groupby');
                $(this).focus();
                alert(1);
});

Add an id to your anchor

<a href="#something" id="myAnchor">Something</a>

Bind a click event and prevent default

$("#myAnchor").click(function(event){
  event.preventDefault();
  return false;
});

如果您将“ new_div_1”作为新添加的div的ID,并将焦点移至新添加的div,则可以

$("body").animate({ scrollTop: $('#new_div_1').offset().top }, 1000);

尝试将窗口滚动到该div的位置:

 window.scrollTo(0,$("#MY_DIV").offset().top);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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