Floated image to left of a ul is ignoring margin/padding

后端 未结 6 685
暗喜
暗喜 2021-02-07 20:50

I have a paragraph followed by an unordered list, with several list items. I also have an image floated to the left of that. The problem I am having is that the list item margin

6条回答
  •  长发绾君心
    2021-02-07 21:18

    If you don't bother about adding javascript, here is a jQuery script that will add a margin to the ul that overlaps the image so all the list items remain aligned, and then assigns a negative margin to the li's that doesn't overlap.

    $(function(){
        //Define a context so we only move lists inside a specified parent
        var context = $("#test_div");    
    
        //Build a list of images position a size
        var imgRects = [];
        var imgs = $("img.left", context);
        imgs.each(function(i){
            var pos = $(this).position();
            pos.right = pos.left + $(this).outerWidth(true);
            pos.bottom = pos.top + $(this).outerHeight(true);
            imgRects.push(pos);        
        });
    
        //Process each li to see if it is at the same height of an image        
        var lis = $("li", context);
        lis.each(function(i){
            var li = $(this);
            if(li.parent().css('marginLeft') != "0px"){
                return; //Already moved
            }
            var top = li.position().top;
            for(var j in imgRects){
                var rect = imgRects[j];
                if(top > rect.top && top < rect.bottom){
                    li.parent().css('marginLeft', rect.right);
                    return;
                } else if(li.parent().css('marginLeft') != "0px"){
                    li.css('marginLeft', -1 * rect.right);
                }
            }
        });
    });
    

    I've tested with your demo page and jQuery 1.3.2 and it works on FF3.5 and IE8 because the image is on top of the document. If the image appears in the middle of a ul, the firsts li's will remain padded. If you need to correct this issue leave a comment and will try to update the script.

提交回复
热议问题