我有一个脚本,当页面加载时,它会“飞入”一个 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/