开发者

How to change the left attribute on page resize (jQuery)

开发者 https://www.devze.com 2023-03-19 16:22 出处:网络
I\'m having slight troubles with my code. What I\'m trying to do is make these element\'s css property \'left\' update according to the difference of it\'s current left value, and the amount the page

I'm having slight troubles with my code. What I'm trying to do is make these element's css property 'left' update according to the difference of it's current left value, and the amount the page resizes. This way, when the page resizes and the background moves over, the elements will move too. Take a look at the code below and I'll describe the issue:

$(window).resize(function() {
    var docWidth = $(window).width();
    if (docWidth < 1000) {
        var difference = 1000-docWidth;
        $('#headNav a,#icons div').each(function() {
            var left = $(this).position().left;
            var newLeft = left - difference;
            $(this).css({ 'left' : newLeft });
     开发者_Python百科   });
    }
});

So the issue that I'm getting is the elements are being given left values of wild numbers, while the value of the variable 'newLeft' is the reasonable, desired value. The each function I think is collecting the sums of these values and running them for each element x amount of times that the elements found exist (so if there's 5 elements it runs 5 times, I mean.) What I want is this code to execute uniquely for each element, but just once each, not each element 10 times! (that's how many elements are in the html).

So my question is, how can this be achieved? I hope I explained myself well enough, this was tough to iterate. Any help is extremely appreciated. Thank you!


Here's a fun trick: Include += in your .css() call:

$(this).css({left: "+=" + difference});

jQuery does the math for you to get the new value.


Try this:

$(window).resize(function() {
    var docWidth = $(window).width();
    if (docWidth < 1000) {
        var difference = 1000-docWidth;            
        $('#headNav a,#icons div').each(function(iconInst) {
            var left = $("#" + iconInst).position().left;
            var newLeft = left - difference;
            $("#" + iconInst).css({ 'left' : newLeft });
        });
    }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消