【问题标题】:inconsistent css height for element using jquery使用jquery的元素的css高度不一致
【发布时间】:2017-10-05 23:17:07
【问题描述】:

我有一个相对简单的 jquery 函数,用于根据父高度设置一个 div 的高度。

(function() {
var $window = $(window);
function resize() {
    if ($window.width() > 800) {
        $(".event-list").each(function() {
          var parentHeight =  $(this).height();
          $(this).children('.text').css("height",parentHeight);
          $(this).children('.pattern').css("height",parentHeight);
        });
    } else {
      $(".event-list").each(function() {
        $(this).children('.text').css("height", 'auto');
        $(this).children('.pattern').css("height", 'auto');
     });
    }
}
$window
    .resize(resize)
    .trigger('resize');
})(jQuery);

你可以在这里看到它的工作原理:http://theadventureschool.com/new-site/events/

在我的本地计算机上,这每次都能正常工作,但是当我实时推送网站时,有时高度是正确的值,有时默认为 22px。

任何解决此问题的帮助将不胜感激。

谢谢, 珍妮

【问题讨论】:

  • 清除浏览器缓存后是否有效?
  • 缓存好像没什么区别。
  • 它在 Chrome 中似乎工作得相当一致,但不是 Safari

标签: javascript jquery html css height


【解决方案1】:

您应该等待图片完成加载。如果我取出图像并调整页面大小,我会得到 22px 的高度。尝试在图像加载时添加一个侦听器,一旦图像完成加载,然后进行初始大小调整。

(function() {
var $window = $(window);
$(".event-list img").load(function() {
    resize();
});
function resize() {
    if ($window.width() > 800) {
        $(".event-list").each(function() {
         var parentHeight =  $(this).height();
         $(this).children('.text').css("height",parentHeight);
         $(this).children('.pattern').css("height",parentHeight);
     });
} else {
  $(".event-list").each(function() {
    $(this).children('.text').css("height", 'auto');
    $(this).children('.pattern').css("height", 'auto');
 });
}
}
$window
    .resize(resize)
    .trigger('resize')
    .load(resize);
})(jQuery);

【讨论】:

  • 这听起来像是一个完美的解决方案,不幸的是我在 jquery 方面有点初学者。你能指出如何添加监听器的正确方向吗?
  • $('.event-list img').load(function() { code goes here });
  • 像这样,就在$(function()之后?好像不行。我也试过用resize()函数加,也没用。
  • $(function() { $('.event-list img').load(function() { var $window = $(window);
  • $(function() { $('.event-list img').load(function() { resize(); } function resize() { resize code} }
【解决方案2】:

$(document).ready() 解决这个问题?

jQuery 文档: https://learn.jquery.com/using-jquery-core/document-ready/

【讨论】:

  • 我在函数中添加了$(function() { ,它似乎仍然有同样的问题。
  • 这个功能应该包含在页面的页眉还是页脚中?
  • 示例:$(document).ready(function() { var $window = $(window); function resize() { ... });
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-05-29
  • 1970-01-01
  • 2017-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多