繁体   English   中英

获取宽度为100%的图像的高度

[英]Get the height of image of 100% width

我正在尝试从浏览器的宽度获取其宽度为100%的图像高度。

$(document).ready(function(){
    var heightImage = $('ul.images img').height();
    $('ul.images').css("height", heightImage + "px");
});

上面代码的问题是,当我调整浏览器的大小,并且100%宽度的图像的高度发生变化时, heightImage不会发生变化。

所以我决定使用:

$(window).resize(function(){
    var heightImage = $('ul.images img').height();
    $('ul.images').css("height", heightImage + "px");
});

上面的代码有两个问题:

图像处于绝对位置。 有时它显示块,有时则不显示。 它会在图像淡入显示以从幻灯片放映之前捕获图像高度。 更改浏览器大小时,它会更改图像的高度。 但是,如果我们在图像褪色时调整浏览器的大小,而所有图像均不显示,它将捕获图像的高度为0px。

该代码的第二个问题是它仅在浏览器大小更改时才检测图像的高度。

谁能给我一种替代方法,即如何在调整放映器大小时以100%+的宽度捕捉幻灯片上图像的高度?

提前致谢。

我的HTML代码

<ul class="images">
   <li><img src="1.jpg" /></li>
   <li><img src="2.png" /></li>
   <li><img src="3.jpg" /></li>
   <li><img src="4.jpg" /></li>
</ul>

我只是从下面的某个地方复制粘贴此代码:

var triggers = $('ul.triggers li');
var images = $('ul.images li');
var lastElem = triggers.length-1;
var target;

triggers.first().addClass('active');
images.hide().first().show();

function sliderResponse(target) {
    images.fadeOut(500).eq(target).fadeIn(500);
    triggers.removeClass('active').eq(target).addClass('active');
}

triggers.click(function() {
    if ( !$(this).hasClass('active') ) {
        target = $(this).index();
        sliderResponse(target);
        resetTiming();
    }
});

$('.next').click(function() {
    target = $('ul.triggers li.active').index();
    target === lastElem ? target = 0 : target = target+1;
    sliderResponse(target);
    resetTiming();
});
$('.prev').click(function() {
    target = $('ul.triggers li.active').index();
    lastElem = triggers.length-1;
    target === 0 ? target = lastElem : target = target-1;
    sliderResponse(target);
    resetTiming();
});

function sliderTiming() {
    target = $('ul.triggers li.active').index();
    target === lastElem ? target = 0 : target = target+1;
    sliderResponse(target);
}

var timingRun = setInterval(function() { sliderTiming(); },5000);
function resetTiming() {
    clearInterval(timingRun);
    timingRun = setInterval(function() { sliderTiming(); },5000);
}

这样做:

var heightImage = $('ul.images img').height();
$(window).resize(function(){
    heightImage = $('ul.images img').height();
    $('ul.images').css("height", heightImage + "px");
}).resize();

编辑2:

一种简单的方法是将整个内容编写到函数中,如果高度为0,则在循环中调用它。

function setHeight(){
    var imageHeight=$('ul.images img').height();
    if(imageHeight==0){
        clearTimeout(window.TO);
        window.TO=setTimeout(setHeight(),100);
    }
    else{
        $('ul.images').css("height", imageHeight + "px");
    }
}
setHeight()
$(window).resize(function(){
    setHeight()
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM