,可以通过以下步骤实现:
以下是一个示例代码:
<!DOCTYPE html>
<html>
<head>
<style>
#myDiv {
width: 200px;
height: 200px;
background-color: yellow;
position: static;
bottom: auto;
}
</style>
</head>
<body>
<div id="myDiv">This is a div element.</div>
<script>
window.addEventListener('scroll', function() {
var div = document.getElementById('myDiv');
var rect = div.getBoundingClientRect();
var originalPosition = rect.top; // 获取div的原始位置
if (window.pageYOffset >= originalPosition) {
div.style.position = 'fixed';
div.style.bottom = '0';
} else {
div.style.position = 'static';
div.style.bottom = 'auto';
}
});
</script>
</body>
</html>
这段代码会在滚动到div的原始位置时,将div的位置从固定位置切换到最底部,再切换到初始位置。你可以将其复制到一个HTML文件中,然后在浏览器中打开该文件,进行测试。
领取专属 10元无门槛券
手把手带您无忧上云