原生JS实现分享侧边栏

2022-04-15 0 1,068

本文分享一个用原生JS实现的分享侧边栏,实现效果如下:

原生JS实现分享侧边栏

以下是代码实现,方便大家复制粘贴。

<!DOCTYPE html>
<html>
 
<head lang="en">
    <meta charset="UTF-8">
    <title>分享到效果</title>
    <style>
        #share {
            position: fixed;
            width: 100px;
            height: 200px;
            background-color: lightblue;
            left: -100px;
            top: 100px;
        }
 
        #share span {
            width: 20px;
            height: 60px;
            line-height: 20px;
            text-align: center;
            left: 100px;
            top: 70px;
            position: absolute;
            background-color: yellow;
        }
    </style>
 
</head>
 
<body>
 
    <div id="share">
        <span>分享到</span>
    </div>
 
    <script>
        // 获取元素
        var share = document.getElementById("share");
        // 将事件设置给share
        share.onmouseover = function () {
            animate(this, "left", 0);
        };
        share.onmouseout = function () {
            animate(this, "left", -100);
        };
 
        // animate运动函数
        function animate(tag, attr, target) {
            clearInterval(tag.timer);
            tag.timer = setInterval(function () {
 
                // 获取某个属性的当前状态
                // 由于具有单位,需要取整
                // parseInt("hehe") => NaN    NaN || 0
                // 为了应对auto转换为NaN的问题,我们使用短路操作,保证程序的健壮性
                var leader = parseInt(getStyle(tag, attr)) || 0;
 
                // 缓动公式的一部分是更改step的值
                var step = (target - leader) / 10;
 
                // 由offsetLeft在取值的时候会四舍五入,step如果比较小,会造成无法运动的问题
                // 根据步数的正负,更改取整方式
                step = step > 0 ? Math.ceil(step) : Math.floor(step);
 
                // 缓动公式
                leader = leader + step;
 
                // 设置给某一个属性
                tag.style[attr] = leader + "px";
 
                // 检测是否走到了指定位置
                if (leader == target) {
                    clearInterval(tag.timer);
                }
            }, 17);
        }
 
        // 用于获取某个标签的某个样式属性值
        // 带单位
        function getStyle(tag, attr) {
            // 检测支持哪一个
            // box.currentStyle,如果不存在值为undefined
            // getComputedStyle如果浏览器不支持。相当于变量未声明,报错
            if (tag.currentStyle) {
                // ie支持
                return tag.currentStyle[attr];
            } else {
                // 标准方法
                return getComputedStyle(tag, null)[attr];
            }
        }
 
    </script>
</body>
 
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持NICE源码。

免责声明:
1、本网站所有发布的源码、软件和资料均为收集各大资源网站整理而来;仅限用于学习和研究目的,您必须在下载后的24个小时之内,从您的电脑中彻底删除上述内容。 不得使用于非法商业用途,不得违反国家法律。否则后果自负!

2、本站信息来自网络,版权争议与本站无关。一切关于该资源商业行为与www.niceym.com无关。
如果您喜欢该程序,请支持正版源码、软件,购买注册,得到更好的正版服务。
如有侵犯你版权的,请邮件与我们联系处理(邮箱:skknet@qq.com),本站将立即改正。

NICE源码网 JavaScript 原生JS实现分享侧边栏 https://www.niceym.com/26200.html