动态宽度= jQuery的高度

Dynamic Width = Height with jQuery

本文关键字:高度 jQuery 动态      更新时间:2023-09-26

我在互联网上搜索了几个小时,但没有找到解决这个小问题的方法:制作一个小脚本来保持动态高度相对于宽度。

我可以使用函数来做到这一点,但这些函数只局限于类等,我有一个动态表单$(this),但我想为每个div单独加载函数与类或数据。

我的HTML示例:

<section>
    <div>
        <figure data-image="height80">
            <img src="[MYIMG]" alt="Image" />
        </figure>
    </div>
</section>
<section>
    <div class="large">
        <figure data-image="height80">
            <img src="[MYIMG]" alt="Image" />
        </figure>
    </div>
</section>
我的JS (with data):
height80();
$(window).resize(function() {
    height80();
});
function height80() {
  var photo80 = $('[data-image="height80"]');
  var photo80W = photo80.width() * 0.8;
    photo80.css({ 'height': photo80W, 'max-height': photo80W });
}
有了这个,我需要为每个不同的div大小创建一个函数,所以:有一种方法来创建一个完整的功能优化函数来做到这一点?

PS:我已经尝试使用$(this),但它返回body的宽度…= (

谢谢!

#这里小提琴#

我想你的问题是你访问this的范围。

尝试更新您的height80函数:

function height80() {
    $('[data-image="height80"]').each(function () {
        var width80 = $(this).width()*0.8;
        $(this).css({ 'height': width80, 'max-height': width80 });
    });
}

这是一个更新的小提琴:

http://jsfiddle.net/Da9HT/

不不不…使用jQuery.call。这将作用域转移到另一个函数。我在用我的Nexus自动取款机,所以我不能给你链接。然后,在这个函数中,你可以使用$(this),它将对这个函数调用的所有元素是动态的。