【问题标题】:How to add white space in Bootstrap until certain element is on top of screen?如何在 Bootstrap 中添加空格,直到某些元素位于屏幕顶部?
【发布时间】:2022-01-02 10:40:42
【问题描述】:

我的网站上有这张图片,它在 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 中我没有固定的空间测量,但直到图像到达顶部。

【问题讨论】:

  • 是否可以发布重现问题的示例代码?
  • @DavidSalomen ,我已经插入了我的代码和我希望它如何实现的示例。

标签: javascript html css bootstrap-4


【解决方案1】:

如果您只想在单击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 中的职位不熟悉,最好查看this documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 1970-01-01
    • 1970-01-01
    • 2010-11-16
    相关资源
    最近更新 更多