简体   繁体   中英

Scroll horizontal overflow div center with javascript

I have a horizontal ul as tabbar inside a div. When i click on a li element, i want to scroll the parent div center to the viewport. How can i do that without jquery?

 const tab1 = document.getElementbyId('tab1'); const tabbar = document.getElementbyId('tabbar'); if (tab1) { tabbar.scrollLeft = -tabbar.offsetWidth } else { tabbar.scrollLeft = tabbar.offsetWidth } 
 <div id="tabbar" class="container"> <ul class="tabbar"> <li id="tab1"><a>Tab 1<a/></li> <li id="tab2"><a>Tab 2<a/></li> <li id="tab3"><a>Tab 3<a/></li> </ul> </div> 

What exactly do I need to change about this function so that the container scrolls horizontally into the middle at each resolution when you click on the second li element?

First get all elements and then add an event listener on each of them.
Then, in the event listener function, find the height of the parent element and height of the screen.
Now, apply the screen top to the window as per the calculations above.

JS:

var tabs = document.querySelectorAll(".tablinks");

tabs.forEach(function(tab) {
  tab.addEventListener("click", function() {
    var parentDiv = document.getElementById("uix-tabbar");
    var sTop = (parentDiv.clientHeight/2) + (screen.height/2);
    window.scrollTo(0, sTop);
  });
});


Let me know in case any more info is required. Hope it helps!

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