首页 > 解决方案 > 将 onload 函数与 onresize 函数连接

问题描述

我想根据屏幕大小缩短一些 API 标题。所以我有一个 onload 函数来获取和显示 API 的内容,但我希望一个 onresize 函数在屏幕宽度的大小发生变化的任何时候都可以生效。

window.onload = function displayNews(width){
   fetch('some api url')
   .then(res => {
      return (res.json())
   })
   .then(function(res) {
    let postsArr = res.data.children;

    for (let i = 0; i < postsArr.length; i++) {
      let currPost = postsArr[i].data;
      let currPostTitle = currPost.title;

      if (width > 1525) {
         currPostTitle = currPostTitle.substring(0, 100) + '&hellip;';
      } else if (width < 1525 && width > 1090) {
         currPostTitle = currPostTitle.substring(0, 20) + '&hellip;';
      } else if (width < 1090) {
         currPostTitle = currPostTitle.substring(0, 200) + '&hellip;';
      }

      let markup = 
      `
      //(Some API display)

然后我创建了将宽度变量传递给 onload 函数的 onresize 函数

window.onresize = function windowWidth() {
   let width = $(window).width();
   displayNews(width);
}

但它不起作用,我不知道在哪里放置 onresize 函数。我试图将它放在 onload 中,但也许我犯了一个错误。你怎么看?

标签: javascriptapiwidthonloadonresize

解决方案


推荐阅读