jQuery, JavaScript and vue let the child box scroll to the specified position of the parent box, including setting the value of scrollTop to the specified position rem


foreword

需求:移动端商品列表中有10个数据,默认展示5个,希望点击更多商品的时候,展示的最后一个自动滚动到最上面
It is mainly to summarize the pitfalls encountered when js and jq use scrolling boxes


这里是基本html和css结构,以下的都根据这个来

<div id="father">
    <div id="son">
      11111111111111111111111122222222222222222222222222222223333333333333333333333333334444444444444444444444444444444555555555555555555555555555556666666666666666666777777777777777777
    </div>
  </div>
  <button id="btn" onclick="myBtn()">点我滚动</button>
/* css代码 */
#father{
    
    
  width: 100px;
  height: 200px;
  background-color: skyblue;
  overflow: auto;
}
#son{
    
    
  width: 100px;
  background-color: pink;
  word-break: break-all;
}

Knowledge point 1: word-break可以设置盒子内容超出盒子自动撑开
word-break: normal|break-all|keep-all;
normal means to use the browser's default line break rules.
break-all means to allow line breaks within words.
keep-all means that only half-width spaces or hyphens can be broken.

1. JavaScript scrolls to the specified position with animation

1: How to scroll the box to the specified position? (scrollTop and scrollLeft)

Anyone who knows the scroll family among the three major JavaScript families knows that the syntax for getting and setting the scroll position is as follows

Get scroll position: element.scrollTop
Set scroll position: element.scrollTop = value

The truth is correct, but I stepped on a big pit when I didn't use it very much. Look directly at the code! ! ! ! ! ! ! !

const father = document.getElementById('father');
const son = document.getElementById('son');
const btn = document.getElementById('btn');
// 按钮的点击事件
function myBtn(){
    
    
  console.log('我被点击了',son.scrollTop);
  // son.scrollTop  = 150; // 没效果
  father.scrollTop  = 150; // 点击按钮后滚动到3的位置,如下图
}

insert image description here
As shown in the figure above: After clicking the button, using the child element .scrollTop to set the scroll position has no effect, and the parent element sets the value of scrollTop to have the effect of scrolling, so in terms of preparation, it should be correct to obtain 父元素.scrollTopand modify the scroll position. I always thought it was a sub-box to be rolled for a long time, and finally tested it with a demo. . . . . .

2. Understand the scrollTo method in JavaScript

Detailed explanation of the scrollTo method in mdn: https://developer.mozilla.org/zh-CN/docs/Web/API/Element/scrollTo

(1) Function

Element's scrollTo() method can make the interface scroll to the specified coordinate position of the given element.

(2) Grammar
element.scrollTo(x-coord, y-coord)
element.scrollTo(options)
(3) parameters

The x-coord is the desired scroll position in pixels from the top-left corner of the element on the horizontal axis.
The y-coord is the desired scroll position in pixels from the top-left corner of the element on the vertical axis.
options is a ScrollToOptions object.

(4) use
const father = document.getElementById('father');
const son = document.getElementById('son');
const btn = document.getElementById('btn');
function myBtn(){
    
    
   // 设置盒子滚动的值
  // father.scrollTop  = 150;
  // scrollTo方式一:
  father.scrollTo(0, 150); // x轴不滚动,y轴滚动150px
  // scrollTo方式二:
  father.scrollTo({
    
    left: 150, behavior: 'smooth'}); // x轴平滑滚动150px
  father.scrollTo({
    
    top: 150, behavior: 'smooth'}); // y轴平滑滚动150px
  father.scrollTo({
    
    top: 15, left: 150, behavior: 'smooth'}); // x轴平滑滚动15px,y轴平滑滚动150px
}

Knowledge point 2: The value of behavior can be selected as auto to jump directly, and smooth to proceed smoothly

3. JavaScript how to set scrollTop to the specified position as rem

3.1 Ideas

As we all know, in js, the value set by scrollTop has no code, which means that rem cannot be used directly to change the position, so we need to work around it. First of all, you need to know that the value of rem is changed through font-size in html. If the value of font-size is 16, then 1rem is 16px. Here we directly get the value of font-size in html and then remove the unit of px by cutting the string. Here we assume that each product is 32px, and one product is 2rem, that is, moving to the fifth one is 8rem, so I get the following code.

const father = document.getElementById('father');
let htmlFontSize = document.documentElement.style.fontSize.replace('px',''); // html的font-seze的值
document.getElementById('father').scrollTo({
    
    top: htmlFontSize * 8, behavior: 'smooth'}); // 滚动4个商品的距离,看到的就是第五个了

3.2. Supplement: If the above code does not get the value of font-size, or the value is empty, please use the following method

Knowledge point 3
(0) Address: window.getComputedStyle method in mdn: https://developer.mozilla.org/zh-CN/docs/Web/API/Window/getComputedStyle
(1) Function: Return an object that reports the values ​​of all CSS properties of an element after applying the active style sheet and parsing any basic calculations these values ​​may contain. Private CSS property values ​​can be accessed through the API provided by the object or by simply indexing using the CSS property name.
(2) Syntax: document.defaultView.getComputedStyle(element[,pseudo-element]);
window.getComputedStyle(element[,pseudo-element]);
(3) Parameter 1: element (required) is used to obtain the Element of the computed style.
Parameter two: pseudoElt (optional) Specifies a string of pseudo-elements to match. Must be omitted (or null) for normal elements.

So we can use the window.getComputedStyle method to get the font-seze value of html

const father = document.getElementById('father');
let htmlFontSize = getComputedStyle(window.document.documentElement)['font-size'].replace('px',''); // html的font-seze的值
document.getElementById('father').scrollTo({
    
    top: htmlFontSize * 8, behavior: 'smooth'}); // 滚动4个商品的距离,看到的就是第五个了

4. Code collection of all the above JavaScript

const father = document.getElementById('father');
const son = document.getElementById('son');
const btn = document.getElementById('btn');
function myBtn(){
    
    
  // 设置盒子滚动的值
  // father.scrollTop  = 150;

  // scrollTo方式一:
  // father.scrollTo(0, 150); // x轴不滚动,y轴滚动150px
  
  // scrollTo方式二:   behavior的值可选  auto为直接跳到,smooth为平滑进行
  // father.scrollTo({left: 150, behavior: 'smooth'}); // x轴平滑滚动150px
  // father.scrollTo({top: 150, behavior: 'smooth'}); // y轴平滑滚动150px
  // father.scrollTo({top: 15, left: 150, behavior: 'smooth'}); // x轴平滑滚动15px,y轴平滑滚动150px
}
//onscroll事件的处理函数
// son.onscroll = function readScrollTop() {
    
    
//   console.log('scrollTop:', outEle.scrollTop); // 可以清楚的看到滚动的距离
// }
// document.getElementById('son').scrollTo({top: 170, behavior: 'smooth'}); // 滚动大概3个渠道的距离
let htmlFontSize = document.documentElement.style.fontSize.replace('px',''); // html的font-seze的值
document.getElementById('father').scrollTo({
    
    top: htmlFontSize * 8, behavior: 'smooth'}); // 滚动4个商品的距离,看到的就是第五个了

2. jQuery scrolls to the specified position with animation

The above is very detailed. The syntax of jq is different. Here is a brief note.

1.$(document).ready()和window.onload

(1)onload()的方法是在页面加载完成后才发生,这包括DOM元素和其他页面元素(例如图片)的加载。
(2)$(document).ready()所要执行的代码是在DOM元素被加载完成的情况下执行,所以,使用document.ready()方法的执行速度比onload()的方法要快。
Why this sudden mention? Because you write jq code, you must write it here, otherwise it will have no effect. I also noticed it after reading the scrollTop example of jq
insert image description here

Test address: https://www.runoob.com/try/try.php?filename=tryjquery_css_scrolltop_get

2. jQuery's animate method

The w3c above is very detailed, so I won’t make a fuss here. The animate method of jquery in w3c can be used directly in the code

$('#father').animate({
    
    
   scrollTop: 150  // 这里也可以是scrollLeft,也就是修改侧轴的位置
}, 500); // 500 为滑动事件,可以修改,单位是ms

3. jQuery sets the value of scrollTop to the specified position to rem

This is the same as setting scrollTop to the specified position by JavaScript in 1.3. The value is rem.

let htmlFontSize = getComputedStyle(window.document.documentElement)['font-size'].replace('px',''); // html的font-seze的值
$('#channel_list').animate({
    
    
  scrollTop: htmlFontSize * 8    // 这里就是使用rem设置scrollTop的值了
}, 500);

Three: Vue scrolls to the specified position with animation

In fact, JavaScript can be used, and vue can also be used. They all use the scrollTo method, mainly to talk about the use of ref

parent.scrollTo(x, y);  // 注意,是父盒子.scrollTo
this.$refs.parent.scrollTo(0, 300); // ref的使用(注意:需要设置ref才能使用)

Note: If you are sure that the dom element and the scrooTo method are used correctly, you can put the method in nextTick.

Summarize

The above summarizes the basic use of scrollTop in JavaScript and jQuery, the use of scrollTop in animation, and the use of rem to change the value of scrollTop, where scrollLeft is used in the same way.

Supplement - scrollIntoView

1: function

只能滚动顶部底部中间,无法滚动到指定位置。

2: use

// javascript
父元素.scrollIntoView(); //顶部
父元素.scrollIntoView(false); //底部
父元素.scrollIntoView({
    
     behavior: "smooth", block: 'center' }); /中间
// vue 
this.$refs.父元素Ref.scrollIntoView({
    
     behavior: "smooth", block: 'center' });  ref的使用(注意:需要设置ref才能使用)

behavior is the same as the scrollInTo method: auto means to jump directly, and smooth means to proceed smoothly

Guess you like

Origin blog.csdn.net/weixin_44784401/article/details/129366073