本篇内容主要讲解“原生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怎么实现分享侧边栏”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。