切换背景图像,然后调整图像大小以适应新的高度'用jQuery

时间:2014-09-21 10:54:54

标签: jquery

我有以下内容:

HTML:

<div id="section-one" class="section">
    <img id="section-one-img" style="width: 100%;" src="http://176.67.174.179/ukcctvinstallations.co.uk/wp-content/uploads/2014/09/section-one-pointers.jpg" />
    <div id="section-one-headline">
    <h1 class="main-headline"><span class="site-colour border-box">Your local CCTV Company</span> <br /><p class="headline-desc">with over 80 installation teams NATIONWIDE</span></h1>
    </div>
</div>

jQuery的:

jQuery(document).ready(function() {
    if (jQuery(window).width() < 880) {
    jQuery('#section-one-img').attr("src", 'http://176.67.174.179/ukcctvinstallations.co.uk/wp-content/uploads/2014/09/section-one-880px.jpg');
    }
    var imgHeight = jQuery('#section-one-img').height();
    jQuery('#section-one-img').height(imgHeight);
});

虽然它在屏幕尺寸<1时加载了正确的新图像。 880,它没有设置图像的新高度(图像的底部被截断)。

我的代码中有什么问题需要解决吗?

2 个答案:

答案 0 :(得分:1)

load() function更改后,您必须使用src作为图片:

Fistly。应创建具有新图像的元素(DOM)并立即计算其尺寸。那么我们可以调整它们: 由于这个原因,请查看jsfiddle.net/csdtesting/81r4ktj4/1/

实施

jQuery(document).ready(function() {
    if (jQuery(window).width() < 880) {  
        var img = 'http://176.67.174.179/ukcctvinstallations.co.uk/wp-content/uploads/2014/09/section-one-880px.jpg';          

        var pic_real_width, pic_real_height;
        $("<img/>") // Make in memory copy of image to avoid css issues
            .attr("src", img)
            .load(function() {
                pic_real_width = this.width;   // Note: $(this).width() will not
                pic_real_height = this.height; // work for in memory images.
                /*alert(pic_real_width);
                alert(pic_real_height);*/
            });    
   jQuery('#section-one-img').attr("src", 'http://176.67.174.179/ukcctvinstallations.co.uk/wp-content/uploads/2014/09/section-one-880px.jpg');
          jQuery('#section-one-img').height(pic_real_height);
    }
});

希望它有所帮助!

答案 1 :(得分:0)

为什么不让CSS处理高度,而不是设置所有固定大小:

JS:

jQuery(document).ready(function() {
    if (jQuery(window).width() < 880) {
    jQuery('#section-one-img').attr("src", 'http://176.67.174.179/ukcctvinstallations.co.uk/wp-content/uploads/2014/09/section-one-880px.jpg');
    }
   // removed height setting here
});

CSS:

img {
    height: auto;
}

jsFiddle:http://jsfiddle.net/6cktLr4h/

但是,当你使用媒体查询只用CSS显示/隐藏不同的图像时,为什么甚至会使用jQuery呢? See this answer