如何仅在屏幕调整为特定宽度时使用 JQuery 调用函数



如何让下面的这个函数仅在屏幕大小调整为特定宽度(如媒体查询(时才调用?(特别是600px最大宽度,在此演示中。

这是我到目前为止开发的内容,但我一定没有做正确的事情......

$(function() {
  if ($(window).screen.width <= 600) {
    $(".content").each(function(t) {
      len = $(this).text().length, len > 5 && $(this).text($(this).text().substr(0, 5) + "...")
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="content">CONDENSE THIS TEXT</span>

添加window.onresize,这将捕获调整大小事件:

$(function() {
  window.onresize = function(event) {
    if (window.screen.width <= 600) {
      $(".content").each(function(t) {
        var len = $(this).text().length;
        if (len > 5) $(this).text($(this).text().slice(0, 5) + "...")
      });
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="content">CONDENSE THIS TEXT</span>

jQuery 没有 screen 属性,请使用 window.screen 。请注意,使用逗号运算符将len定义为后面的表达式的结果,

$(function() {
  if (window.screen.width <= 600) {
    $(".content").each(function(t) {
      var len = $(this).text().length;
      if (len > 5) $(this).text($(this).text().slice(0, 5) + "...")
    });
  };
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="content">CONDENSE THIS TEXT</span>

找到了一个解决方案:

function checkWidth() {
  if ($(window).width() < 600) {
    $('#content').addClass('fulltxt');
    $("#content").each(function(i) {
      len = $(this).text().length;
      if (len > 5) {
        $(this).text($(this).text().substr(0, 5) + '...');
      }
    })
  } else {
    $('#content').removeClass('fulltxt');
    $("#content").each(function(i) {
      $(this).text($(this).data('originaltxt'));
    });
  }
}
$("#content").each(function() {
  $(this).data({
    originaltxt: $(this).text()
  });
});
$(window).resize(checkWidth);
#content {
  border: 2px solid green;
  display: inline-block;
  padding: 5px;
}
#content.fulltxt {
  border-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="content">CONDENSE THIS TEXT</div>

只需使用 jQuery width()

$(function() {
  if ($(window).width() <= 1000) {
    $(".content").each(function(t) {
      len = $(this).text().length, len > 5 && $(this).text($(this).text().substr(0, 5) + "...")
    });
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="content">CONDENSE THIS TEXT</span>

最新更新