How to resize image on mobile devices using jQuery?

梦想的初衷 提交于 2021-01-27 15:50:39

问题


I am working on a mobile website and I have a div & image inside it like this:

<div id="wrapper">
    <div id="content">My img tag here</div>
</div>

I want to know, how I can resize the image on any phone/tablet without worrying about its resolution, size or orientation. Here, I am looking for the best possible solution based on the above scenarios.


回答1:


You can use media queries to give CSS attributes depending on the orientation:

@media screen and (orientation:portrait) {
    img {
        // css attributes
    }
}

@media screen and (orientation:landscape) {
    img {
        // css attributes
    }
}

Or you could do it for screen width:

@media screen and (max-width: 500px) {
    img {
        // css attributes
    }
}



回答2:


The above mentioned technique is the most widespread, but as i understand the solution desired shouldn't be dependent about device size, screen resolution or orientation.

I only mention two clever solution, none of them handle this job on CSS:

https://github.com/adamdbradley/foresight.js

http://adaptive-images.com/

The second solution is clever one, because it captures the screen resolution of visitor's device, automatically creates caches and deliver the most appropriated image size of embedded html <img> markup.

Note: One mention though: this is server dependent solution, and should be used only in PHP code environment.

...and here is a jquery plugin which for the same purposes: https://github.com/teleject/hisrc




回答3:


I found a simple solution using jquery....

$(document).ready(function() {

    $width = $('#content').width();

    $('#content img').css({
        'max-width': $width,
        'height': 'auto'
    });
});



来源:https://stackoverflow.com/questions/14009378/how-to-resize-image-on-mobile-devices-using-jquery

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