zoukankan      html  css  js  c++  java
  • 各类距离计算(持续更新中...)

    1.元素到可视窗口顶端的距离

    $('XXX').offset().top-$(document).scrollTop();  //jq
    XXXX.getBoundingClientRect().top   //js
    // 举例应用,制作顶飘
    //$(window).scrollTop() >=
    $('XXX').offset() //元素超出视口高度,在视口的上方
     

    2.判断元素是否在视口内

    function isVisible($node) {
        var windowH = $(window).height(),// 窗口高度  视口高度
            scrollH = $(window).scrollTop(), // 滚动条高度
            $nodeOffsetH = $node.offset().top, // 元素距离文档顶部的高度
            $nodeHeight = $node.outerHeight(); // 元素自身高度 没用true 因此不包含margin
        if (!(scrollH > ($nodeOffsetH + $nodeHeight - 5) || (scrollH + windowH) < $nodeOffsetH)) {
            // 这里减5 为修正值 点击a 标签锚点定位时 有2px左右的误差
            return true
        } else {
            return false
        }
    
    }     
    //js版
    const elementIsVisibleInViewport = (el, partiallyVisible = false) => { const { top, left, bottom, right } = el.getBoundingClientRect(); const { innerHeight, innerWidth } = window; return partiallyVisible ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; }; // 事例 elementIsVisibleInViewport(el); // 需要左右可见 elementIsVisibleInViewport(el, true); // 需要全屏(上下左右)可以见

    3.获取元素最终样式

    与style的区别,style只会读取内联样式,

    getComputedStyle会获取内联,外联,外部的最终样式

    getComputedStyle(node).marginLeft;    //举例:获取元素的左边距

    4.通过拖拽导航距离,计算居中的activeindex

    //nav_box为导航子集的父级
    //containerWidth 为nav_box的父级
    function getChoose() {
        var left = getComputedStyle(nav_box).marginLeft;  //如果是scroll,可以改为scroll相关距离
        left = parseFloat(left) - containerWidth / 2;
        left = Math.abs(left);
        var i = left / config.optionWidth;
        i = Math.round(i);
        return config.options[i];
    }

    5.导航条根据activeindex动态,计算scrollLeft距离,使active居中

    fuction  handleLeft(){           
                var item = $(navActiveCls);  //active
                var itemOffset = item.offset();
                var itemOffsetLeft = itemOffset.left + this.$navFather.scrollLeft();
                var centerLeft = (this.$nav.width() - item.width()) / 2;
                this.$navFather.stop().animate({
                    scrollLeft: itemOffsetLeft - centerLeft
                })
            }
  • 相关阅读:
    PageAdmin Cms系统如何修改点击数(浏览数)
    最简js深浅拷贝说明
    实用的前端网址
    js的一些编码问题
    自己写一个文字过长显示省略号的函数
    垂直居中 和 水平居中
    js原码工具集
    url 、src 、href 的区别
    transform对定位元素的影响
    css实现一色多变化
  • 原文地址:https://www.cnblogs.com/wxyblog/p/12881997.html
Copyright © 2011-2022 走看看