【问题标题】:How to get height of an image when bootstrap modal is show?显示引导模式时如何获取图像的高度?
【发布时间】:2015-11-08 14:50:12
【问题描述】:

请帮我为此编写 jQuery:

我在引导模式中有这个 HTML 源代码:

<div class="product-preview nospace">
    <div class="product-thumb-list product-image-list">
        <img class="img-responsive" src="images/products/product-1-l.jpg" data-zoom-image="images/products/product-22-l.jpg" alt="product-thumb">
        <img class="img-responsive" src="images/products/product-2-l.jpg" data-zoom-image="images/products/product-22-l.jpg" alt="product-thumb">
        <img class="img-responsive" src="images/products/product-3-l.jpg" data-zoom-image="images/products/product-33-l.jpg" alt="product-thumb">
        <img class="img-responsive" src="images/products/product-4-l.jpg" data-zoom-image="images/products/product-44-l.jpg" alt="product-thumb">
    </div>
    <div class="product-thumb product-image">
        <img class="img-responsive zoom-image" src="images/products/product-1-l.jpg" data-zoom-image="images/products/product-11-l.jpg" alt="product-img">
    </div>
</div>

在 JS 中我这样写:

$('.modal-quickview').on('show.bs.modal', function () {

    $('.zoom-image').click("bind", function() {
        var height =$(this).css('height');

        alert(height);
     });
});

现在我想获取图像的高度,但没有点击之类的操作。

如何修改该脚本?有人请帮帮我吗?我是 JS 的新手。

【问题讨论】:

  • 您也可以尝试有关 JQuery 的课程或书籍。

标签: javascript jquery twitter-bootstrap modal-dialog bootstrap-modal


【解决方案1】:

您可以像这样直接访问选择器上的 .css() 函数:

var height = $(".zoom-image").css("height");

请注意,使用类作为 jQuery 选择器很可能会返回多个项目(如果多个标签具有 zoom-image-class 和 .css() 然后将返回第一个返回项目的高度。最好将唯一 ID 附加到图像并使用该 ID。像这样:

<img id="displayedImage" class="img-responsive zoom-image" (...)>

然后使用 ID 选择器:

var height = $("#displayedImage").css("height");

注意:你应该看看.css("height").height()的区别。见here

编辑:也许你的问题是使用show.bs.modal,你可以试试shown.bs.modal。见here

【讨论】:

  • 感谢您的回答。是的,我已经尝试过,但是使用普通 div 中的图像可以获得正确的高度,但是使用引导模式中的此图像,所以它总是首先返回 0px。我不知道如何为此写更多。
【解决方案2】:

怎么样:

$('.modal-quickview').on('show.bs.modal', function () {
    var height = $(this).find('.zoom-image').css('height');
});

如果您不想获取 css 高度值而是实际图像高度,请改用:$(this).find('.zoom-image').height();

更新

我会建议与 Keeper 相同。请改用shown.bs.modal。您看到 0px 的原因很可能是因为在您尝试确定它的高度时您的图像不可见。如果您使用shown.bs.modal 事件,则模态框已经可见,因此图像具有可确定的高度。

Working Example

【讨论】:

  • 感谢您的快速回答,但我不知道为什么当我提醒(高度)时;它说:0px;您还有其他建议吗?
  • 你必须使用事件 shown.bs.modal。它绝对有效。请参阅我的工作示例。
  • 感谢大家帮助我,我确实喜欢这样,但是当 alert(height) 时它总是显示 0
【解决方案3】:

获取高度的一种可能方法是在点击图片时计算它:

$('.modal-quickview').on('show.bs.modal', function () {
    $('.zoom-image').click("bind", function() {
        var height =$(this).css('height');
        alert(height);
    });
});

我不想点击图片来获取高度值,但是,这可能会帮助其他想要这样做的人!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-02-09
    • 1970-01-01
    • 1970-01-01
    • 2013-01-03
    • 2018-09-07
    • 2013-02-24
    • 1970-01-01
    相关资源
    最近更新 更多