web 12-js小知识集锦

107 阅读3分钟

for与forEach的

forEach

js中foreach是用于遍历数组的方法,将遍历到的元素传递给回调函数,遍历的数组不能是空的要有值。 forEach方法中的function回调有三个参数:
第一个参数是遍历的数组内容,
第二个参数是对应的数组索引,
第三个参数是数组本身

区别

1.for循环可以使用break跳出循环,但forEach不能。

2.for循环可以控制循环起点(i初始化的数字决定循环的起点),forEach只能默认从索引0开始。

3.for循环过程中支持修改索引(修改 i),但forEach做不到(底层控制index自增,我们无法左右它)。

解决Cannot set property 'display' of undefined问题

原因:

class类不能简单直接拿来判断,因为具有多个class。因为class名不唯一。

解决方法:

1)直接改用id名,简单粗暴
2)用class,加上数组判断

z-index 属性指定一个元素的堆叠顺序。

拥有更高堆叠顺序的元素总是会处于堆叠顺序较低的元素的前面。

注意:  z-index 进行定位元素(position:absolute, position:relative, or position:fixed)。

html设置文字无法选中的方法

 .un_select {
     -webkit-user-select:none;
     -moz-user-select:none;
     -ms-user-select:none;
     user-select:none;

}

回到顶部 scrollTop

1.锚点

<body style="height:2000px;">
    <div id="topAnchor"></div>
    <a href="#topAnchor" style="position:fixed;right:0;bottom:0">回到顶部</a>
</body>

【2】scrollTop

  scrollTop属性表示被隐藏在内容区域上方的像素数。元素未滚动时,scrollTop的值为0,如果元素被垂直滚动了,scrollTop的值大于0,且表示元素上方不可见内容的像素宽度

  由于scrollTop是可写的,可以利用scrollTop来实现回到顶部的功能

<body style="height:2000px;">
    <button id="test" style="position:fixed;right:0;bottom:0">回到顶部</button>
    <script>
        test.onclick = function(){
            document.body.scrollTop = document.documentElement.scrollTop = 0;
        }
    </script>
</body>

【3】scrollTo()

  scrollTo(x,y)方法滚动当前window中显示的文档,让文档中由坐标x和y指定的点位于显示区域的左上角

  设置scrollTo(0,0)可以实现回到顶部的效果

<body style="height:2000px;">
    <button id="test" style="position:fixed;right:0;bottom:0">回到顶部</button>
    <script>
        test.onclick = function(){
            scrollTo(0,0);
        }
    </script>
</body>

【4】scrollBy()

  scrollBy(x,y)方法滚动当前window中显示的文档,x和y指定滚动的相对量

  只要把当前页面的滚动长度作为参数,逆向滚动,则可以实现回到顶部的效果

<body style="height:2000px;">
    <button id="test" style="position:fixed;right:0;bottom:0">回到顶部</button>
    <script>
        test.onclick = function(){
            var top = document.body.scrollTop || document.documentElement.scrollTop
            scrollBy(0,-top);
        }
    </script>
</body>

【5】scrollIntoView()

  Element.scrollIntoView方法滚动当前元素,进入浏览器的可见区域 

  该方法可以接受一个布尔值作为参数。如果为true,表示元素的顶部与当前区域的可见部分的顶部对齐(前提是当前区域可滚动);如果为false,表示元素的底部与当前区域的可见部分的尾部对齐(前提是当前区域可滚动)。如果没有提供该参数,默认为true

  使用该方法的原理与使用锚点的原理类似,在页面最上方设置目标元素,当页面滚动时,目标元素被滚动到页面区域以外,点击回到顶部按钮,使目标元素重新回到原来位置,则达到预期效果

<body style="height:2000px;">
    <div id="target"></div>
    <button id="test" style="position:fixed;right:0;bottom:0">回到顶部</button>
    <script>
        test.onclick = function(){
            target.scrollIntoView();
        }
    </script>
</body>