调整窗口大小时如何流动图像?

时间:2013-10-25 15:03:06

标签: javascript jquery html css

调整窗口大小时如何使图像流畅?

我有这样的HTML代码:

<div class="box">
 <img src="http://demo.smooththemes.com/magazon/wp-content/uploads/2013/01/984632486_9d8ff89b63_b-642x336.jpg" />
</div>

和CSS:

.box {width:150px; height:60px; position:relative; overflow:hidden}
.box img{position:absolute; width:180px; height:80px; top:-10px; left:-10px}

调整窗口大小时,我想删除(.box img)的属性:top:-10px; left:-10px并将属性更多:min-width:100%, max-width:100%。这意味着我们有:

.box img{
position:absolute;
width:180px; height:80px; min-width:100%;  
top:(removed); left:(removed)}

如何使用Javascript或Jquery执行此操作。谢谢你的帮助。

4 个答案:

答案 0 :(得分:3)

我不知道jQuery或Javascript解决方案,但如果你想要一个纯CSS解决方案, CSS媒体查询可能就是你想要的。它是响应式网页设计的基本概念。有关CSS媒体查询的更多信息,请访问:https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Media_queries

答案 1 :(得分:3)

我倾向于同意@Phorden的观点,即媒体查询是一条很好的途径。

但是,如果需要使用JS / jQuery执行此操作:

$(window).resize(function() {
    $('.box img').css({'top': 'auto', 'left': 'auto', 'min-width': '100%'});
});

答案 2 :(得分:1)

为图片添加max-width:100%和height:auto,使其根据父级调整比例:

.box img{
       position:absolute; 
       top:-10px; 
       left:-10px

       max-width: 100%; /* fits width of parent */
       height: auto;  /* resize height based on max-width, making it proportional *?
 }

答案 3 :(得分:1)

我认为Scott Jehl的这个剧本对你来说很有意思,尽管图像只会在特定的断点处改变尺寸。

picturefill

它非常有用,因为您可以为各种分辨率定义不同的图像源。

与此脚本结合使用所需的标记例如像这样:

<span data-picture data-alt="Image description">
    <span data-src="small.jpg"></span>
    <span data-src="medium.jpg"     data-media="(min-width: 400px)"></span>
    <span data-src="large.jpg"      data-media="(min-width: 800px)"></span>
    <span data-src="extralarge.jpg" data-media="(min-width: 1000px)"></span>

    <!-- Fallback content for non-JS browsers. Same img src as the initial, unqualified source element. -->
    <noscript>
        <img src="external/imgs/small.jpg" alt="Image description">
    </noscript>
</span>
相关问题