2016-08-07 18 views
0

Ich habe drei Bilder in <section>Position Elemente dynamically- jQuery

<section class="one"> 
      <img src="one.png" /> 
     </section> 

     <section class="two"> 
      <img src="two.png" /> 
     </section> 

     <section class="three"> 
      <img src="three.png" /> 
     </section> 

Ich habe einige CSS hinzugefügt, um die Abschnitte zu positionieren:

$('.one').css({ 
     position:'absolute', 
     top:100 
    }); 
    $('.two').css({ 
     position:'absolute', 
     top:800 
    }); 

    $('.three').css({ 
     position:'absolute', 
     top:1600 
    }); 

Mein Problem ist in den js - ich möchte, dass jeder positionieren Element dynamisch so zum Beispiel der erste Abschnitt wäre top 100px der Abschnitt wäre 200px und der dritte wäre 300px. Dies ist, was ich bisher geschafft haben:

$.fn.inView = function(){ 
    var win = $(window); 
    obj = $(this); 
    var scrollPosition = win.scrollTop(); 
    var visibleArea = win.scrollTop() + win.height(); 
    var objEndPos = (obj.offset().top + obj.outerHeight()); 
    var visible =(visibleArea >= objEndPos && scrollPosition <= objEndPos); 
    $.each(obj, function(index) { 
     if(visible){ 
      //console.log(index); 
      $(obj).css({ 
       position:'fixed', 
       top: index*100//Problem here 

      }); 
     } 
    }); 
}; 

Antwort

1

Sie hatte Das Hauptproblem war, dass Sie die CSS des obj jQuery-Selektor setzen und nicht auf dem img, die in der obj Selektor war.
Um das img Element, um Sie innerhalb der $.each, die das aktuelle Element ist ein von $(this) oder fügen Sie einen zweiten Parameter an die Callback-Funktion verwenden:

$.each(obj, function(index, el) { 
    $(el).css 

Dies ist der komplette Schnipsel:

$(function() { 
 
    obj = $('section img'); 
 
    $.each(obj, function(index) { 
 
    $(this).css({ 
 
     position:'fixed', 
 
     top: index*100 
 
    }); 
 
    }); 
 
});
section img { 
 
    width: 50px; 
 
    height: 50px; 
 
    border: 1px solid black; 
 
} 
 
section.one img { 
 
    border-color: red; 
 
} 
 
section.two img { 
 
    border-color: green; 
 
} 
 
section.three img { 
 
    border-color: blue; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<section class="one"> 
 
    <img src="one.png" alt="one"/> 
 
</section> 
 
<section class="two"> 
 
    <img src="two.png" alt="two" /> 
 
</section> 
 

 
<section class="three"> 
 
    <img src="three.png" alt="three" /> 
 
</section>