I'm having difficulty with jQuery's $(selector).each()

不问归期 提交于 2019-12-23 13:09:49

问题


Example here: http://jsfiddle.net/KyW6c/2/

I have an ordered list. Each list item is a project in my portfolio. I'm writing some jQuery that will move a clicked list item up to the top left of the ordered list. I've accomplished this, but the problem I'm encountering is that the list items below the clicked one are shifting. This code is provided in the fiddle (commented out).

The solution I'm attempting to implement will set each list item's position to absolute and left and right to it's current position within the ordered list once the page is loaded. I don't know if I'm having trouble because I misunderstand what .each() does, or just how to implement it.

Thanks.

EDIT: The problem is that each list item's left and top values are being set to 0, so they're all just overlapping on at the top left. If you uncomment the jQuery, you'll see the problem.

EDIT 2: I discovered that if I don't set the position to absolute at the same time that I set the left and top properties, it works properly.


回答1:


The problem was as you iterated through each element, you were setting 'postion:absolute' which was removing the current element from the positioning. As each element is "removed" from the layout, the following element floats to the 0,0 position.

By iterating from the bottom up, you're able save the left/top first, then apply postion:absolute without affecting the next element:

  $($('.project').get().reverse()).each(function(){
    var pos = $(this).position();
    $(this).css({
      left: pos.left + 'px',
      top: pos.top + 'px',
      position: 'absolute',
      'z-index': '999'
    })
  });

  // your original code
  $('.project').click(function(){
    var $this  = $(this),
        left = $this.position().left + 'px',
        top  = $this.position().top + 'px';
    $this.css({
      left:      left,
      top:       top,
      position:  'absolute',
      'z-index': '999'
    }).animate({
      left:       0,
      top:        0,
      width:      '750px'
    }, 'fast', 'swing')
  }); 



回答2:


http://jsfiddle.net/KyW6c/11/

Got it figured out with a little help from a friend. Thanks, Matt!




回答3:


$('.project').ready().each(..)

should be

$('.project').each(..)

you can try something like this:

  var left = 0,
      top = 0;
$('.project').each(function(){
    var $this  = $(this),
    $this.css({
      left:      (left+10) + 'px',
      top:       (top+10) + 'px',
      position:  'absolute',
      'z-index': '999'
    })
  });


来源:https://stackoverflow.com/questions/10476571/im-having-difficulty-with-jquerys-selector-each

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!