javascript - 调整浏览器大小时 jQuery 重新运行脚本

标签 javascript jquery

我有一个脚本,当页面加载时,它会“飞入”一个 div,其位置基于窗口的宽度,但是当用户重新调整浏览器大小时,它看起来不正确并且失去了效果。我是 jQuery 新手,有没有办法在浏览器调整大小时重新运行脚本,或者更改我的脚本,以便在调整浏览器大小时它可以工作。

<script type="text/javascript">
$(window).load(function() {
var currWidth = $(window).width();

var element = 170; //size of the element
var put = (currWidth / 2) - element; //work out the margin left to put the element

$('#welcome').animate({left: put}, 1000);
});
</script>

最佳答案

您可以收听$(window).resize()事件。

 $(function(){
     resizeEm();
 });
 var $window = $(window);
 $window.resize(function() {
    //Run your script or invoke the function
    resizeEm();
 });

 function resizeEm(){
     var currWidth = $window.width();
     var element = 170; //size of the element
     var put = (currWidth / 2) - element; //work out the margin left to put the element
     $('#welcome').animate({left: put}, 1000);
 }

调整大小事件很容易在一次调整大小时触发多次,因此您可以使用 setTimeout 保留一个计时器,并根据任意超时值执行一次调整大小。

 var timeout;
 $window.resize(function() {
    //Run your script or invoke the function
   clearTimeout(timeout); //if any events fire previous existing timeout in the event queue gets cleared
   timeout = setTimeout(function(){ //create a new timeout
    resizeEm();
    }, 500); //Just giving 500 millisec delay
 });

<强> Demo

关于javascript - 调整浏览器大小时 jQuery 重新运行脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20507047/

相关文章:

javascript - 在按钮单击事件上渲染新的 react 组件

javascript - 如何使用 Google Maps DirectionsService.route() 函数中的 Angular 双向绑定(bind)?

javascript - 在 JavaScript 不起作用的情况下启动 Google+ 登录流程

javascript - 在 Rails 应用程序中使用 json 对象的更好方法

javascript - 找到值之间匹配的最简单方法是什么

jquery - 实现从 Google AJAX 库 API 到本地 jQuery 的回退

javascript - jQuery/JavaScript trim 包含空格/空行的 HTML

javascript - 你能初始化一个函数吗? - Javascript

javascript - 安卓浏览器 : get scale factor

jquery - 根据文本框更改更新字段 jQuery