Using jQuery to change image src when browser is resized

前端 未结 4 900
慢半拍i
慢半拍i 2021-01-14 01:45

I have two different sized images, one if for screens smaller than 759px, the other is for screens larger than 759px.

I have managed to get the source of the images

相关标签:
4条回答
  • 2021-01-14 02:24

    First try this...

    change your follwoing line of code

    $(window).bind("resize", function(){//Adjusts image when browser resized
            imageresize();
        });
    

    to

    // Bind event listener
        $(window).resize(imageresize);
    

    and put alert inside imageresize to see if it works or not...

    In case above do not work out...I believe there is one problem probably..

    in your code you have

    $(document).ready(function() {
    
     $(window).bind("resize", function(){//Adjusts image when browser resized
            imageresize();
        });
    }
    

    So the function for reside inside jquery which may not work well. On top of that try using simple javascript; i had similar problem and solved using plain javascript and jquery did not work in some browsers.

    Sound strange enough to stop you try at it but would work...

    0 讨论(0)
  • 2021-01-14 02:26

    It's not jQuery but you can simple use document.getElementById("myId").src="another.jpg"; to define the new src of the img with id "myId".

    0 讨论(0)
  • 2021-01-14 02:41

    Try to use css3 media queries instead of doing it in jQuery or javascript.

    http://css-tricks.com/media-queries-sass-3-2-and-codekit/

    Consider using "img-src" class on a . Whenever the screen is resized b/w 600px to 900px; x2.jpg will be loaded. By default x1.jpg will be used.

    Ex:

    .img-src {
       background-image: url("http://imageurlhere.com/x1.jpg");
    }
    
    
    @media (min-device-width:600px) and (max-width:900px) {
      .img-src {
          background-image: url("http://imageurlhere.com/x2.jpg");
       }
    }
    
    0 讨论(0)
  • 2021-01-14 02:43

    Your code works fine, as I can see, but I prefer to use setTimeout, some times page could slow down without resize pause.

    $(document).ready(function() {
        var resizeTimer,
            $window = $(window);
    
        function imageresize()
        {
            if ($window.width() < 700)
            {
                $('.fluidimage').text('< 700');
            }
            else
            {
                $('.fluidimage').text('>= 700');
            }
        }
        imageresize();//Triggers when document first loads
    
        $window.resize(function() {
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(imageresize, 100);
        });
     }); 
    

    Example: jsfiddle.net/SAbsG/

    0 讨论(0)
提交回复
热议问题