每日一kun:这世上没谁离不开谁,就算是一条鱼离开水,也能烤着吃。
第一种写法:juejin.cn/post/717632… 这里是第二种写法,出来的效果一样,不过比第一种简洁,第一种不需要CSS定位,现在这种对CSS的定位要求极高,要时刻明白所有DIV与其他元素的定位关系。
JS代码
var span = document.querySelector("span")
var div = document.querySelectorAll("div")
span.addEventListener("mouseenter", function () {
packageTimer(div[1], div[0].offsetWidth - 200, function () {
span.innerHTML = "👉"
})
})
span.addEventListener("mouseleave", function () {
packageTimer(div[1], div[0].offsetWidth, function () {
span.innerHTML = "👈"
})
})
var packageTimer = function (obj, away, comeBack) {
clearInterval(obj.timer)
obj.timer = setInterval(function () {
var step = (away - obj.offsetLeft) / 10
step = step > 0 ? Math.ceil(step) : Math.floor(step)
if (obj.offsetLeft == away) {
clearInterval(obj.timer)
if (comeBack) {
comeBack()
}
}
obj.style.left = obj.offsetLeft + step + "px"
}, 20)
}
HTML代码
<div class="main">
<span>👈</span>
<div class="con">内容显示</div>
</div>
CSS代码
.main {
display: flex;
position: relative;
height: 300px;
margin-top: 200px;
justify-content: flex-end;
background-color: steelblue;
}
span {
background-color: yellowgreen;
width: 50px;
height: 40px;
position: absolute;
text-align: center;
z-index: 10;
line-height: 40px;
right: 0px;
top: 100px;
}
.con {
background-color: yellowgreen;
width: 200px;
height: 40px;
text-align: center;
align-items: center;
position: absolute;
line-height: 40px;
right: -150px;
}
body {
overflow: hidden;
}
结果
