原生JS实现分享侧边栏

发布时间:2022-04-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了原生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>

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

脚本宝典总结

以上是脚本宝典为你收集整理的原生JS实现分享侧边栏全部内容,希望文章能够帮你解决原生JS实现分享侧边栏所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: