0
点赞
收藏
分享

微信扫一扫

原生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>

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

您可能感兴趣的文章:

举报

相关推荐

0 条评论