简体   繁体   English

使用 javascript 加载 HTML 文件

[英]load HTML file with javascript

I need to load the content of an HTML file into a div.我需要将 HTML 文件的内容加载到 div 中。

I am doing it with the following javascript code我正在使用以下 javascript 代码

function scroll_down() {
  var div = $('#div_name');
  $.get('html_file_to_load.html', function(data) { 
      div.html(data);
      $('body, html').scrollTop(div[0].scrollHeight);
  })
}

the function loads the html_file_to_load.html file, add the content to a div, and then scrolls down the page. function 加载 html_file_to_load.html 文件,将内容添加到 div,然后向下滚动页面。 The problem is that the HTML file may contain some pictures问题是HTML文件可能包含一些图片

example < img src='picture.jpg' >示例< img src='picture.jpg' >

In this case what happens is that after the HTML code is loaded, the scroll bar is set to the bottom, the browser loads the pictures and the vertical height of the page increases !!在这种情况下发生的情况是HTML代码加载后,滚动条设置到底部,浏览器加载图片,页面垂直高度增加!!

I need to add a check: the browser has to wait until the HTML file and pictures files eventually included in it are all loaded before executing scrollTop(div[0].scrollHeight);我需要添加一个检查:浏览器必须等到 HTML 文件和最终包含在其中的图片文件都加载完毕,然后再执行 scrollTop(div[0].scrollHeight);

How can I do this?我怎样才能做到这一点?

You can add event listeners to the images and force it to scroll when they load您可以将事件侦听器添加到图像并在加载时强制它滚动

function forceScroll(elem) {
  $('body, html').scrollTop(elem.scrollHeight);
}

function scroll_down() {
  var div = $('#div_name');
  $.get('html_file_to_load.html', function(data) {
      var html = $(data);
      var imgs = html.find("img");
      imgs.each(function() {
        $(this).on("load", function() {
          forceScroll(div[0]);
        });
      });
      div.append(html);
      forceScroll(div[0]);
    }
  });
}

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

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