Coo*_* Yo 13 jquery resize subtraction
我从snipplr使用这个脚本,我如何设置它,使容器div比newWindowHeight高度小100px,如-100或其他东西.
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
//If the User resizes the window, adjust the #container height
$(window).bind("resize", resizeWindow);
function resizeWindow( e ) {
var newWindowHeight = $(window).height();
$("#container").css("max-height", newWindowHeight );
}
});
</script>
Run Code Online (Sandbox Code Playgroud)
Sam*_*son 31
你发现的脚本过于复杂了这个问题.以下对我有用:
$(function(){
// Cache reference to our container
var $container = $("#container");
// A function for updating max-height
function updateMaxHeight () {
$container.css("max-height", $(this).height() - 100);
}
// Call updateMaxHeight when browser resize event fires
$(window).on("resize", updateMaxHeight);
});
Run Code Online (Sandbox Code Playgroud)
一个警告是调整浏览器大小时调用resize事件; 它不仅仅是在浏览器调整大小后调用的.因此,您可以将回调函数调用数百次 - 这通常是一个坏主意.
解决方案是扼杀或去除事件.限制意味着你不会让回调在一段时间内被触发超过x次(可能是每秒5次).去抖意味着您从最后一次调整大小事件(等待调整大小事件后500毫秒)经过一段时间后触发回调.
虽然有插件,但jQuery目前不支持限制或去抖选项.您可能使用过的其他常用库也具有这些功能,例如下划线:
$(function(){
// Cache reference to our container
var $container = $("#container");
// A function for updating max-height
function updateMaxHeight () {
$container.css("max-height", $(this).height() - 100);
}
// Version of updateMaxHeight that will run no more than once every 200ms
var updateMaxHeightThrottled = _.throttle(updateMaxHeight, 200);
// Call updateMaxHeightThrottled when browser resize event fires
$(window).on("resize", updateMaxHeightThrottled);
});
Run Code Online (Sandbox Code Playgroud)