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

时间:2013-12-10 22:52:26

标签: 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>

1 个答案:

答案 0 :(得分:3)

您可以收听$(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);
 }

调整大小事件是gng,可以多次触发一次调整大小,这样你就可以使用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

相关问题