2016-07-25 4 views
1

Я пытаюсь найти лучший способ обновить div с идентификатором «дата» с датами прокрученных проходов. Я думал, что это можно сделать, получив атрибуты date-date, но у меня даже возникли проблемы с получением идентификаторов divs, которые прокручиваются мимо. Таким образом, в этом случае содержание даты div должно начинаться с 25 июля, а затем, когда div с id = 2 передает дату div, содержимое даты div должно измениться до 25 июля и так далее.Как обновить div на основе его позиции относительно другого div

index.html:

<html> 
<head> 
<style> 

#comments { 
float:left; 
width:450px; 
} 

#date { 
position: absolute; 
top: 0; 
margin-top: 20px; 
border: 1px solid #A9F5F2; 
background-color: #A9F5F2; 
color: #6E6E6E; 
font-weight: bold; 
} 

</style> 

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.js">  
</script> 
<script> 
$(document).ready(function() { 

$(function() { 
$(window).scroll(function (event) { 

    var p = $('#date').closest('[id]'); 
    console.log(p); 

}); 
}); 
}); 
</script> 
</head> 
<body> 


<div id="1" data-date="25 July"> 
comment 1 comment 1 comment 1 comment 1 comment 1 comment 1 <p> 
comment 1 comment 1 comment 1 <p> 
comment 1 comment 1 comment 1 <p> 
</div> 

<div id="2" data-date="24 July"> 
comment 2 comment 2 comment 2 comment 2 comment 2 comment 2 <p> 
comment 2 comment 2 comment 2 <p> 
comment 2 comment 2 comment 2 <p> 
</div> 

<div id="3" data-date="23 July"> 
comment 3 comment 3 comment 3 
comment 3 comment 3 comment 3 <p> 
comment 3 comment 3 comment 3 <p> 
comment 3 comment 3 comment 3 <p> 
</div> 

<div id="4" data-date="22 July">comment 4 comment 4 comment 4 
comment 4 comment 4 comment 4 <p> 
comment 4 comment 4 comment 4 <p> 
comment 4 comment 4 comment 4 
</div> 

<div id="5" data-date="21 July"> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
</div> 

<div id="date" style="float:right; position: fixed"> 
    25 July 
</div> 

</body> 
</html> 
+0

Как вы обработка прокрутки? Это по умолчанию прокрутка браузера или какая-то библиотека? – Hodrobond

+0

Просто fyi, .closest вернет ближайший элемент, основанный на dom, а не на положение экрана. Помните, что DOM - это то, с чем будут взаимодействовать любые javascript и html, несмотря на то, что на экране. –

+0

В качестве альтернативы дате и дате даты, вы можете написать свои даты как id = '7-5-2015'. Не совсем уверен, что вы делаете, но я бы обрезал атрибут data и идентифицировал их все с датой. –

ответ

0

Я добавил класс вашей даты дивы, такие как

<div class="myDates" id="1" data-date="25 July">

затем

$(document).ready(function() { 
 

 
     function viewPortCheck(el) { 
 
      function isElementInViewport(el) { 
 
       var rect = el.getBoundingClientRect(); 
 
       return (
 
        rect.top >= 0 && 
 
        rect.left >= 0 && 
 
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && 
 
        rect.right <= (window.innerWidth || document.documentElement.clientWidth) 
 
       ); 
 
      } 
 

 
      function givenElementInViewport(el) { 
 
       return function() { 
 
        if (isElementInViewport(el)) { 
 
         let d = el.dataset.date; 
 
         $('#date').html(d); 
 
        } 
 
       }; 
 
      } 
 

 
      if (window.addEventListener) { 
 
       addEventListener('DOMContentLoaded', givenElementInViewport(el), false); 
 
       addEventListener('load', givenElementInViewport(el), false); 
 
       addEventListener('scroll', givenElementInViewport(el), false); 
 
       addEventListener('resize', givenElementInViewport(el), false); 
 
      } else if (window.attachEvent) { 
 
       attachEvent('DOMContentLoaded', givenElementInViewport(el)); 
 
       attachEvent('load', givenElementInViewport(el)); 
 
       attachEvent('scroll', givenElementInViewport(el)); 
 
       attachEvent('resize', givenElementInViewport(el)); 
 
      } 
 
     } 
 

 
     $(function() { 
 
      $(window).scroll(function (event) { 
 
       let elems = $('.myDates'); 
 
       for(let i = 0; i < elems.length; i++){ 
 
        viewPortCheck(elems[i]); 
 
       } 
 
      }); 
 
     }); 
 
    });
#comments { 
 
     float:left; 
 
     width:450px; 
 
    } 
 

 
    #date { 
 
     position: absolute; 
 
     top: 10px; 
 
     right:10px; 
 
     border: 1px solid #A9F5F2; 
 
     background-color: #A9F5F2; 
 
     color: #6E6E6E; 
 
     font-weight: bold; 
 
     min-width:50px; 
 
    } 
 

 
    .myDates { 
 
     min-height: 30%; 
 
     margin: 10% 10px; 
 
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="date" style="float:right; position: fixed"> 
 
    &nbsp; 
 
</div> 
 

 
<div class="myDates" id="1" data-date="25 July"> 
 
comment 1 comment 1 comment 1 comment 1 comment 1 comment 1 <p> 
 
comment 1 comment 1 comment 1 <p> 
 
comment 1 comment 1 comment 1 <p> 
 
</div> 
 

 
<div class="myDates" id="2" data-date="24 July"> 
 
comment 2 comment 2 comment 2 comment 2 comment 2 comment 2 <p> 
 
comment 2 comment 2 comment 2 <p> 
 
comment 2 comment 2 comment 2 <p> 
 
</div> 
 

 
<div class="myDates" id="3" data-date="23 July"> 
 
comment 3 comment 3 comment 3 
 
comment 3 comment 3 comment 3 <p> 
 
comment 3 comment 3 comment 3 <p> 
 
comment 3 comment 3 comment 3 <p> 
 
</div> 
 

 
<div class="myDates" id="4" data-date="22 July">comment 4 comment 4 comment 4 
 
comment 4 comment 4 comment 4 <p> 
 
comment 4 comment 4 comment 4 <p> 
 
comment 4 comment 4 comment 4 
 
</div> 
 

 
<div class="myDates" id="5" data-date="21 July"> 
 
comment 5 comment 5 comment 5 <p> 
 
comment 5 comment 5 comment 5 <p> 
 
comment 5 comment 5 comment 5 <p> 
 
comment 5 comment 5 comment 5 <p> 
 
comment 5 comment 5 comment 5 <p> 
 
comment 5 comment 5 comment 5 <p> 
 
comment 5 comment 5 comment 5 <p> 
 
comment 5 comment 5 comment 5 <p> 
 
comment 5 comment 5 comment 5 <p> 
 
comment 5 comment 5 comment 5 <p> 
 
comment 5 comment 5 comment 5 <p> 
 
comment 5 comment 5 comment 5 <p> 
 
comment 5 comment 5 comment 5 <p> 
 
comment 5 comment 5 comment 5 <p> 
 
comment 5 comment 5 comment 5 <p> 
 
comment 5 comment 5 comment 5 <p> 
 
</div>

+0

Отлично! Просто хочу, мне нужно, я тестирую его локально, и по какой-то причине он не работает так, как есть в Snippet –

+0

есть ли у вас ошибки в консоли? можете ли вы поделиться ими? – datafunk

+0

Не жаль, что я забрал это назад, я ввел опечатку. Ваш код работает отлично! Еще один вопрос, хотя вы можете прокомментировать свой код, потому что я довольно новичок в Javascript, поэтому было бы удобно. –

2

Вы упускаете много кода, но я бросил это вместе - он обнаружит, когда один DIV попадает в верхней части окна. Надеюсь, это поможет вам, и вы сможете добавить остальную функциональность, в которой вы нуждаетесь.

https://jsfiddle.net/tobyl/uquj897s/

$(window).scroll(function() { 

    var elemPos = $("#3").offset().top - $(window).scrollTop(); 
    var winPos = $(window).scrollTop(); 

    if (elemPos < winPos) { 
    console.log("element is above window top!"); 
    } else { 
    console.log("element has not yet hit the window top."); 
    } 
}); 
+0

Отличный способ получить атрибут, такой как дата-дата, когда div попадает в верхнюю часть окна? –

0

Ok я не имею полное решение, но вот то, что я для вас.

Мы можем использовать scrollLeft() и scrollTop(), чтобы определить положение полосы прокрутки (это определяет положение страницы и к какой дате мы ближе всего к ней).

$(window).scroll(function (event) { 
var left = $(window).scrollLeft(); 
var top = $(window).scrollTop(); 
var IDofElementIamCloseTo = someSuperCoolCalculationFunction(left,top); 

    console.log(IDofElementIamCloseTo); 

}); 

function someSuperCoolCalculationFunction(left, top){ 

//somehow determine how far you have moved and what is closer, maybe you can create a list of key //value pairs or make your divs a fixed width/length. 

} 

Это должно заставить вас двигаться.

EDIT: другие ребята отвечают лучше

0

Я не мог закончить из-за времени, но на основании ответа Тоби этот код получает первое вхождение класса «divDate» и в зависимости от его изменения размера и местоположения до следующего и меняет div с id = «date» ... все еще нужно делать, когда свитки. К сожалению любого плохой английский XD

https://jsfiddle.net/smm7mrqn/

<div class="divDate" id="1" data-date="25 July"> 
    comment 1 comment 1 comment 1 comment 1 comment 1 comment 1 <p> 
    comment 1 comment 1 comment 1 <p> 
    comment 1 comment 1 comment 1 <p> 
</div> 

<div class="divDate" id="2" data-date="24 July"> 
comment 2 comment 2 comment 2 comment 2 comment 2 comment 2 <p> 
comment 2 comment 2 comment 2 <p> 
comment 2 comment 2 comment 2 <p> 
</div> 

<div class="divDate" id="3" data-date="23 July"> 
comment 3 comment 3 comment 3 
comment 3 comment 3 comment 3 <p> 
comment 3 comment 3 comment 3 <p> 
comment 3 comment 3 comment 3 <p> 
</div> 

<div class="divDate" id="4" data-date="22 July">comment 4 comment 4 comment 4 
comment 4 comment 4 comment 4 <p> 
comment 4 comment 4 comment 4 <p> 
comment 4 comment 4 comment 4 
</div> 

<div class="divDate" id="5" data-date="21 July"> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
comment 5 comment 5 comment 5 <p> 
</div> 

<div id="date" style="float:right; position: fixed"> 
    25 July 
</div> 

<script> 
var $currDiv = $(".divDate").first(); 
$(window).scroll(function() { 
    var elemPos = $currDiv.offset().top - $(window).scrollTop(); 
    var elemHeight = $currDiv.css("height"); 
    var winPos = $(window).scrollTop(); 

    if (elemPos <= 0) { 
    $('#date').html($currDiv.attr("data-date")); 
    } 
    if((parseInt(elemPos) + parseInt(elemHeight)) <= 0){ 
    $currDiv = $currDiv.next(".divDate"); 
    } 
}); 
</script> 
+0

HI да это тоже хорошо! Можете ли вы добавить код, чтобы справиться с прокруткой назад? –

Смежные вопросы