如何在Bootstrap中添加空白,直到某个元素出现在屏幕顶部



我的网站上有一张Bootstrap 4中的图片,当点击某个按钮或图片时,我想通过在网站底部添加空白来将图片放在用户屏幕的顶部,因此当我的网站向下滚动时,图片就在顶部屏幕上(我用JS函数计算出了这一点(。如何在网站上不断添加空白,直到图像出现在屏幕顶部?我已经想出了一个解决方案,在CSS中有一个特定的元素,其边距固定,并且在单击时可以看到它,但希望它适用于各种大小的视口。

scrollingElement = (document.scrollingElement || document.body);
function scrollSmoothToBottom (id) {
$(scrollingElement).animate({
scrollTop: document.body.scrollHeight
}, 500);
}
window.onload = function(){
// Make WhiteSpace not on website
document.getElementById("whiteSpace").style.display = "none";
document.getElementById("submitButton").addEventListener("click",function(){
// Once Button is clicked make whitespace visible then scroll to bottom
document.getElementById("whiteSpace").style.display = "block";
scrollSmoothToBottom ();
});
}
.space{
margin:520px; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<center>
<h1 id  = "collegeNameTitle">Name</h1>
<h3>Student Size</h3>
<span class="badge badge-success even-larger-badge" id = "collegeStudentSizeText">10</span>
<h3>Acceptance Rate:</h3>
<span class="badge badge-success even-larger-badge" id = "collegeAcceptanceRateText">10</span>
<h3>Student-Faculty Ratio:</h3><span class="badge badge-success even-larger-badge" id = "collegeRatioText">10</span>
</center>
<center><button id = "submitButton"><img class = "collegeImage"src="sample.png" id  = "collegeImage"></button></center>
<div id = "whiteSpace" class ="space" visibility = "hidden">
</div>

我希望我的网站是什么样子的例子。这是我现在的代码,希望在CSS中我没有固定的空间测量,但直到图像到达顶部。

如果您只想在点击button时将img的位置放在屏幕顶部,那么您可以尝试以下代码:

const theImg = document.getElementById("myImg");
const theBtn = document.getElementById("myBtn");
theBtn.addEventListener("click", function(){
theImg.style.position="fixed";
theImg.style.top=0;
});
body{
height: 100vh;
display: flex;
flex-direction: column;
align-item: center;
justify-content: center;
}
img{
height: 5rem;
width: 100%;
}
<button id="myBtn">Button</button>
<img id="myImg" src="https://www.w3schools.com/css/paris.jpg">

如果您不熟悉css中的位置,最好查看此文档。

最新更新