javascript - 如何让一个部分粘几秒钟然后一直粘
问题描述
在网站 - 右侧面板有三个广告,我想要的 - 应该有 3 个广告 前两个广告应该固定几秒钟,然后第三个广告应该很长时间。我正在使用此代码,其中第三个广告,即广告的第二部分在滚动到达其位置时是粘性的,
<div class="right-panel">
<div id="adsection1">
<!--ad1-->
<br/>
<!--ad2-->
</div>
<div id="adsection2" style="width: 300px; height: 600px;">
<div id="abc_ad1">
<!--ad3-->
</div>
</div>
<script>
if (window.innerWidth > 1024) {
var adElem = document.getElementById('adsection2');
window.onscroll = function () {
var rect = adElem.getBoundingClientRect();
adElem.style.width = rect.width + 'px';
adElem.style.height = rect.height + 'px';
document.getElementById('abc_ad1').style.width = rect.width + 'px';
document.getElementById('abc_ad1').style.height = rect.height + 'px';
if (rect.top <= 0) {
document.getElementById('abc_ad1').style.position = "fixed";
document.getElementById('abc_ad1').style.top = "0";
document.getElementById('abc_ad1').style.zIndex = "2147483647";
} else {
document.getElementById('abc_ad1').style.position = "";
document.getElementById('abc_ad1').style.top = "";
document.getElementById('abc_ad1').style.zIndex = "";
}
};
}
</script>
</div>
考虑此链接上的正确部分(我想像它一样设计),https://www.tutorialspoint.com/python_blockchain/python_blockchain_client_class.htm
解决方案
您实际上并不需要 JavaScript 来实现所描述的效果。
诀窍是正确格式化您的 HTML 布局 - 这也意味着将其划分为适当的部分,以便您为粘性元素拥有正确的父级。
旁注:为了简单起见,我使用 div,但在现实生活中的应用程序中,您应该选择语义 HTML。
body, html {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
}
#content {
height:200%;
width: 100%;
}
.col {
height: 100%;
width:50%;
float: left;
}
#main {
background: linear-gradient(#58668b, #ffffff);
}
#ads {
position: sticky;
top: 0px;
background-color:#bdeaee;
}
#header {
height:30px;
background-color: #29a8ab;
}
#footer {
height:100px;
background-color: #651e3e;
color: #ffffff;
}
.top-section {
height: 25%;
}
.top-section div {
height: 45%;
background-color:#ffcc5c;
}
.top-section div:not(:last-child) {
margin-bottom:10%;
}
.bottom-section {
height: 30%;
background-color: #ff6f69;
margin-top: 12%;
}
.sticky-content {
width: 100%;
height: 60%;
position: sticky;
top: 0px;
}
<div id="header">Header</div>
<div id="content">
<div id="main" class="col"><p>Main Content</p></div>
<div id="ads" class="col">
<div class="sticky-content">
<div class="top-section">
<div></div>
<div></div>
</div>
<div class="bottom-section"></div>
</div>
</div>
</div>
<div id="footer">Footer</div>
推荐阅读
- javascript - 如何在 word 插件中从 function-file.html 运行函数
- excel - 如何计算条件单元格公式,相邻单元格公式取决于第一个单元格的计算值,而不是打印值?
- android - Flutter - 让应用在设备离线时显示之前获取的数据
- c - 将数组指针传递给调用函数时如何获取索引计数?
- laravel - 迁移期间未找到基表或视图
- ruby-on-rails - Rails 5.2:如何为每个 I18n 键值创建 fields_?
- keras - AttributeError:“函数”对象没有属性“set_model”
- c - Is there a delay between a SET and a GET with the same key in Redis?
- javascript - 当路径有 ../ 时,fs.existsSync() 总是返回 false
- azure - 以隔离方式部署到 Service Fabric 的 Windows 容器无法解析 DNS