2

Можно ли отследить появление элемента в области видимости браузера с помощью css?

4
  • 1
    Через CSS нельзя. Только через JS*
    – De.Minov
    26 авг 2018 в 17:14
  • @Air, не дубликат, т. к. там просят js, а тут - css.
    – Qwertiy
    26 авг 2018 в 23:05
  • @Qwertiy судя по принятому вопросу - автора и js устроил 24 сен 2018 в 10:19
  • @PavelMayorov, ну да, но вопрос-то всё-таки другой...
    – Qwertiy
    24 сен 2018 в 11:42

1 ответ 1

2

С css нет, а вот с помощью небольшого скрипта, можно) Например такого

function getStatus(node) {
  if(node === undefined || node === null) {
    return;
  }
  var opt = {
    top: false,
    down: false,
    center: false,
    big_center: false,
    show: false,
    procent: 0,
    info: ""
  };
  var mTop = 0;
  var top = node.getBoundingClientRect().top;
  var height = node.offsetHeight;
  var mBottom = document.documentElement.clientHeight;

  if((top) <= mTop && (top + height >= mTop && top + height <= mBottom)) {
    opt.top = opt.show = true;
    var d =  height - Math.abs(top);
    opt.procent = d*100/height;
  }
  if((top) >= mTop && (top < mBottom && top + height >= mBottom)) {
    opt.down = opt.show = true;
    var d = mBottom - top;
    opt.procent = d*100/height;
  }
  if((top) >= mTop && (top + height <= mBottom)) {
    opt.center = opt.show = true;
    opt.procent = 100;
  }
  if((top) < mTop && (top + height > mBottom)) {
    opt.big_center = opt.show = true;
    opt.procent = 100;
  }

  opt.info = "top:["+opt.top+"]"+"down:["+opt.down+"]"+"center:["+opt.center+"]"+"big_center:["+opt.big_center+"]"+"show:["+opt.show+"]"+"procent:["+opt.procent+"]";

  return opt;
};

window.addEventListener("scroll", function() {
  var o = document.querySelectorAll(".main div")[5];
  document.getElementById("message").innerHTML = "[6]"+getStatus(o).info;
}, false);
.main div {
  border: 1px solid black;
  min-height: 80px;
  background-color: #000;
  margin: 10px;
  font-size: 100px;
  color: white;
  font-weight: bold;
  text-align: center;
  line-height: 80px;
}
.main div:nth-child(6) {
  background-color: green;
}
div.top {
  position: fixed;
  border: 1px dotted red;
  width: 100%;
  height: 0px;
  top: 0px;
}
div.bottom {
  position: fixed;
  border: 1px dotted red;
  width: 100%;
  height: 0px;
  bottom: 0px;
}

#message {
  background-color: white;
  color: black;
  position: fixed;
  top: 20%;
  width: 70%;
  padding: 10px;
  z-index: 3;
}
<div class="main">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
  <div>5</div>
  <div>6</div>
  <div>7</div>
  <div>8</div>
  <div>9</div>
  <div>10</div>
</div>
<div class="top"></div>
<div class="bottom"></div>
<div id="message"></div>

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.