javascript - 影响未链接到它的 div 的脚本
问题描述
每当我向下滚动时,我都使用此脚本来隐藏标题,并在向上滚动时再次显示它。
var currentScrollPos = window.pageYOffset;
if (prevScrollpos > currentScrollPos) {
document.getElementById("header").style.top = "0";
} else {
document.getElementById("header").style.top = "-55px";
}
prevScrollpos = currentScrollPos;
}
它工作正常。
但同样的事情发生在另一个 div 上,其代码如下:
<div class="pricing">
<h2>Our Plans</h2>
<button type="button" name="button" class="commonBtn" id="bookBtn"> Buy Now</button>
</div>
<div id="book">
<div id="closeBtn">
x
</div>
<script type="text/javascript">
var bookBtn = document.getElementById("bookBtn");
var book = document.getElementById("book");
book.style.bottom = "-1000px";
bookBtn.onclick = function(){
if (book.style.bottom=="-1000px") {
book.style.bottom="-100px";
}
var closeBtn = document.getElementById("closeBtn");
closeBtn.onclick = function(){
if (book.style.bottom=="-100px"){
book.style.bottom="-1000px";
}
}
}
</script>
这本书的 div 在向上滚动时也会显示一部分,向下滚动时会隐藏。
为什么会发生这种情况,我该如何解决?
提前感谢您的帮助。
PS:它只发生在移动设备中。在 Chrome DEV TOOLS 中也可以正常工作。
标题区
<header class="header" id="header">
<nav class="sidebar" id="sidebar">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About Us</a></li>
<li><a href="#">Plans</a></li>
<li><a href="#">Offers</a></li>
<li><a href="#">Sign Up</a></li>
<li><a href="#">Contact Us</a></li>
<li><div class="custom-control custom-switch">
<input type="checkbox" class="custom-control-input" id="darkSwitch" /> </ul>
</nav>
<div class="container">
<div class="masthead">
<div class="mastheadLeft">
<img src="image/logo.png" class="headerLogo">
</div>
<div class="mastheadRight">
<div id="menuBtn">
☰
</div>
</div>
</div>
</div>
</header>
标题和书籍 div 的 CSS。
#book{
width: 100%;
height: 100vh;
position: fixed;
bottom: -1000px;
background: #0079e3;
transition: 2s;
z-index: 2;
}
.header{
position: fixed;
top: 0px;
left:0px;
right:0px;
z-index: 10;
background-color: #fff;
transition: 0.5s;
}
解决方案
问题在于使用像素和百分比。该问题已通过使用vh
代替px
and解决%
。
正确的代码如下:
<script type="text/javascript">
var bookBtn = document.getElementById("bookBtn");
var book = document.getElementById("book");
book.style.bottom = "-100vh";
bookBtn.onclick = function(){
if (book.style.bottom=="-100vh") {
book.style.bottom="-100px";
}
var closeBtn = document.getElementById("closeBtn");
closeBtn.onclick = function(){
if (book.style.bottom=="-100px"){
book.style.bottom="-100vh";
}
}
}
</script>
#book{
width: 100%;
height: 100vh;
position: fixed;
bottom: -1000px;
background: #0079e3;
transition: 2s;
z-index: 2;
}
这是正确的 javascript 和 css 代码。问题出在这两个部分,剩下的都很好。
推荐阅读
- c# - C# DataTable 分组并汇总成新的 DataTable
- swift - 设置 Lottie 动画的约束 - swift
- unity3d - Unity 的 Android 权限功能如何工作?
- python - 如何在 argparse python 中创建多个自定义操作?
- php - 在 php mysql 中将 varchar 数据类型转换为日期
- apache - .htaccess/apache - 尝试静默重定向到基于子域的文件时出现“404 错误”
- java - 试图让我的 while 循环使用符合条件的值,而不是给定 java 的第一个输入
- java - 所有 jComboBox 都相互镜像
- python - Python中的抛物线SAR ....PSAR不断增长而不是逆转
- java - 使用 java lock 或 catch 数据库异常