• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

原生JS实现分享侧边栏

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文分享一个用原生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>

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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Vite+Electron快速构建VUE3桌面应用的实现发布时间:2022-02-05
下一篇:
原生JS实现登录框邮箱提示发布时间:2022-02-05
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap