When you make a music player, you need to scroll the lyrics

The lyrics need to be synchronized in the middle, how to achieve this effect?



usejQueryEasy Dom manipulation

Key steps

  1. Wrap each lyric in a LI label and place it in an OL or UL label
  2. Set the width and height of the OL TAB that needs to display the lyrics
  3. Ol labelCSS style useoverflow: auto;
  4. Calculate the height center of the middle position of the OL label
  5. Move the first line of the song to the middle:$("ul").css("padding-top",center)
  6. The formulalet top = $("ul").scrollTop()-($("ul").offset().top-currentLyric.offset().top) - centerorlet top = currentLyric[0].offsetTop - $("ul")[0].offsetTop - center
  7. $("ul").animate({scrollTop: top})


The key function

scrollTop()

Gets the offset of the matched element relative to the top of the scrollbar. This method works for both visible and hidden elements

offset()

Gets the relative offset of the matched element in the current viewport. The returned object contains two integer attributes, top and left, in pixels. This method works only on visible elements

offsetTop

Htmlelement. offsetTop is a read-only property that returns the distance of the current element relative to the top inner margin of its offsetParent element.

The sample

Jsfiddle.net/wayaya/3hae…