如何在页面顶部粘贴div

时间:2017-01-10 15:41:08

标签: javascript html css

我只想把div放在页面顶部

如果有人滚动页面,则绿色div stickdiv应自动粘贴在顶部

var left = document.getElementsByClassName("stickdiv");

for( var i = 0;i<left.length;i++){
var stop = (left[0].offsetTop);

window.onscroll = function (e) {
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
    if (scrollTop >= stop) {
     left.className += " stick"; //adding a class name
    } else {
        className = '';
    }

}
}

为什么在div上添加stick类不起作用 - https://jsfiddle.net/kzk5qab2/1/

我只想把div放在顶部,就像黄色div一样 - http://jsfiddle.net/qc4NR/

2 个答案:

答案 0 :(得分:4)

您已经循环进入left项的数组,但在尝试将类名添加到元素时忘记引用数组索引。

&#13;
&#13;
var left = document.getElementsByClassName("stickdiv");

for (var i = 0; i < left.length; i++) {
  var stop = (left[0].offsetTop);

  window.onscroll = function(e) {
    var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
    // left.offsetTop;
    if (scrollTop >= stop) {
      // get array item by index
      left[0].classList.add('stick'); //adding a class name
    } else {
      // get array item by index
      left[0].classList.remove('stick');
    }
  }
}
&#13;
.stickdiv {
  height: 50vh!important;
  width: 100vh!important;
  background-color: green!important;
}
.stick {
  position: fixed;
  top: 0;
  margin: 0 0
}
#right {
  float: right;
  width: 100px;
  height: 1000px;
  background: red;
}
.des {
  height: 300px;
  width: 100%;
  background-color: #000;
}
&#13;
<div class="des"></div>
<div class="stickdiv"></div>
<div id="right"></div>
&#13;
&#13;
&#13;

如果直接选择项目,您甚至不需要循环,如下所示:

var left = document.querySelector(".stickdiv");
var stop = (left.offsetTop);

window.onscroll = function(e) {
  var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
  // left.offsetTop;
  if (scrollTop >= stop) {
    left.classList.add('stick'); //adding a class name
  } else {
    left.classList.remove('stick');
  }
}

答案 1 :(得分:0)

根据您需要支持的浏览器,您不一定需要使用JS。

.sticky {
    position: sticky;
    left: 0;
    top: 0;
    width: 100%;
}

Codepen: https://codepen.io/afisher88/pen/xJaxoP

浏览器支持粘贴位置:https://caniuse.com/#search=position%3A%20sticky