首页 > 解决方案 > 如何在特定的 div 中定位修复按钮?

问题描述

按钮显示position: fixed仅在第二个 div 内具有属性。当我滚动到第一个或最后一个 div 时,按钮不应该固定在它们上,这意味着按钮应该只在第二个 div 内可见,我该怎么做?

.one{
                height:600px;
                width: 100%;
                background-color: red;
            }
            .two{
                height:600px;
                width: 100%;
                background-color: yellow;
            }
            .three{
                height:600px;
                width: 100%;
                background-color: pink;
            }
            .mybutton{
                width:80px;
                height: 20px;
                position: fixed;
                right:10px;
                top:100px;
            }
<html>
    <head>
        <body>
            <div class="one">                
              <button class="mybutton">Click</button>
            </div>
            <div class="two"></div>
            <div class="three"></div>
        </body>
    </head>
</html>

标签: javascripthtmlcss

解决方案


这是一种方法,尽管我不知道它是否是您要寻找的方法。position:sticky在按钮和position:relative容器上使用( .two)

.one {
  height: 600px;
  width: 100%;
  background-color: red;
}

.two {
  height: 600px;
  width: 100%;
  background-color: yellow;
  position: relative;
}

.three {
  height: 600px;
  width: 100%;
  background-color: pink;
}

.mybutton {
  width: 80px;
  height: 20px;
  position: sticky;
  right: 10px;
  top: 100px;
}
<div class="one"></div>
<div class="two"><button class="mybutton">Click</button></div>
<div class="three"></div>


推荐阅读