Why do

Recently in the process of internship received such a demand, web page display of an article, on the right side needs to have a list of the title of the article, at the same time the article at the time of rolling rolling to the corresponding title when the corresponding title needs to change color, and click on the corresponding position of the title to jump to the corresponding title, here with js native implementation, because of my reason for level, There are many flaws, for reference only.

Let’s use draw. IO for a quick diagram

Get the title

getTitle: function (markdown) { let template = Array.from(markdown.querySelectorAll('h1,h2,h3,h4,h5,h6')); // Get all the titles on the page let length = template-length; for (let i = 0; i < length; i++) { template[i].setAttribute('id', `${template[i].tagName}${i}`); }// Add the id to the title, and prepare the return template for adding the anchor later; }Copy the code

Create a list of articles and add anchors

Createlist (data) {// pass in the title list from the previous function. Let ul = document.createElement('ul'); for (let j of data) { let li = document.createElement('li'); let a = document.createElement('a'); a.appendChild(document.createTextNode(`${j.innerText}`)); / / copies header content to a label on a.s etAttribute (' href '` # ${} j.i d `); // add the anchor li.appendChild(a); if (j.tagName === 'H2') li.style.paddingLeft = '15px'; If (j.tagname === 'H3') li.style.paddingLeft = '30px'; ul.appendChild(li); } return ul; }Copy the code

Rolling color logic

scroll(page, list) { let article = page.querySelector('.page-article'); let h = Array.from(article.querySelectorAll('h1,h2,h3,h4,h5,h6')); Let alist = Array. From (list.querySelectorAll('a')); Onscroll = function () {for (let I of h) {let distance = i.offsettop - article.scrollTop; If (distance > 0 && distance < 20) {// let id = i.getattribute ('id'); For (let j of Alist) {j.style.color = 'black'; let href = j.getAttribute('href'); href = href.slice(1, href.length); # if (href === id) j.stile. color = 'blue'; //}}}}; }Copy the code

Finally, set up a flag and try to write one article a day, Orz