简体   繁体   中英

scrollIntoView() works in console but not not when in in the site code

I have a div which contains a table for tabs in my site navigation. I have the div set to overflow when in mobile like this:

在此处输入图片说明

I want to have the div scroll to the, currently hidden, active tab automatically like this:

在此处输入图片说明

In another SA question it was suggested to use scrollIntoView . Tested it in the console and it works fine:

document.getElementById("active_tab").scrollIntoView({block: "end"})

I even used the jQuery version scrollintoview :

$('#active_tab').scrollintoview();

and it works fine. The trouble is that when I add the actual code (either one) to my site the overflow div on scrolls some random amount (seems to be half way). Here is an example:

在此处输入图片说明

Tried this in Chrome and Safari. Am I missing something obvious? I am not trying to scroll the whole page - just that div that has hidden overflow. Very odd that it work direct in the console but not in my code direct and for both JS and JQ. As far as I know there is no other JS etc related to this div etc.

Hard to tell whats going on without seeing it live first-hand (can you link to the live site or make jsfiddle demo?) but i'll make a qualified guess;

It could be that when the scrolling happens programatically the menu isnt completely finished rendering. Maybe icons or the notifications arent showing yet, and so it scrolls to the right on a shorter menu and then widens as things get loaded.

You can test if this is the case by calling the code inside a setTimeout


Edit

A call to setTimeout(fn, 0) will run the fn immediately, but queued. Since this appears to have fixed your isse, it means some other task, that is already queued but has not quite run yet affects the width of the nav bar.

However, it's impossible to say exactly that is without seeing the code running first-hand. To find out yourself you can use the process of elimination :

For instance, try removing the setTimeout again, and remove the icons and see what happens. If you still have the issue, try adding the icons back and removing the notification numbers instead, etc.

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