[英]Using Javascript to resize a div to screen height causes flickering when shrinking the browser window
我試圖用另一個HTML / CSS布局挑戰解決StackOverflow問題-使用jQuery我自己使用粘性頁腳的全高側邊欄 。 因為我的情況下邊欄可能比主要內容長,所以它與評論8128008的情況相符 。 這使得側邊欄比主要內容更長,並且在縮小瀏覽器窗口時不會出現問題而不會出現問題。
我有一個帶有div
的html頁面,它會自動拉伸以填充屏幕。 因此,如果元素下方有空白空間,我將其向下拉伸:
但是如果瀏覽器視口小於div
本身,則不會進行拉伸但滾動條會顯示:
我已經將jQuery附加到窗口的resize事件來調整div
的大小,如果瀏覽器窗口不小,則在其他情況下刪除任何大小調整。 這是通過檢查視口是高於還是小於document
。 如果視口小於document
,則內容似乎比瀏覽器窗口大,為什么沒有進行大小調整; 在另一種情況下,我們調整div
大小以填充頁面。
if ($(document).height() > $(window).height()) {
// Scrolling needed, page content extends browser window
// --> No need to resize the div
// --> Custom height is removed
// [...]
} else {
// Window is larger than the page content
// --> Div is resized using jQuery:
$('#div').height($(window).height());
}
到目前為止,一切運行良好。 但是如果我收縮瀏覽器窗口,有些情況下div
應調整大小,但document
大於window
的高度,為什么我的腳本假設,不需要調整大小並刪除div
的大小調整。
問題實際上,如果我在出現錯誤后使用Firebug檢查document
的高度,那么高度恰好具有該值。 所以我想, document
的高度設置有點延遲。 我試圖運行調整大小的代碼延遲了一點,但它沒有幫助。
我已經在jsFiddle上建立了一個演示。 只需慢慢收縮瀏覽器窗口,您就會看到div
“閃爍”。 你也可以看一下console.log()
輸出,你會注意到,在“閃爍”的情況下, document
的高度與window
的高度不同而不是相等。
我在Firefox 7,IE 9,Chrome 10和Safari 5.1中注意到了這種行為。 你能證實一下嗎?
你知道是否有修復? 或者方法完全錯了? 請幫我。
好的 - 擦掉我的舊答案並替換......
這是你的問題:
您正在考慮並比較窗口和文檔高度,而不首先考慮事件的順序。
此時,div的先前設置高度保持文檔高度大於窗口高度,並且這個邏輯被誤解為:“需要滾動,不需要擴展側邊欄”,錯誤地觸發
因此抽搐。
為了防止它,只需在進行比較之前調整div和窗口的大小:
(function () {
var resizeContentWrapper = function () {
console.group('resizing');
var target = {
content: $('#resizeme')
};
//resize target content to window size, assuming that last time around it was set to document height, and might be pushing document height beyond window after resize
//TODO: for performance, insert flags to only do this if the window is shrinking, and the div has already been resized
target.content.css('height', $(window).height());
var height = {
document: $(document).height(),
window: $(window).height()
};
console.log('height: ', height);
if (height.document > height.window) {
// Scrolling needed, no need to externd the sidebar
target.content.css('height', '');
console.info('custom height removed');
} else {
// Set the new content height
height['content'] = height.window;
target.content.css('height', height['content']);
console.log('new height: ', height);
}
console.groupEnd();
}
resizeContentWrapper();
$(window).bind('resize orientationchange', resizeContentWrapper);
})(jQuery);
根據pmvdb的評論,我將您的$$重命名為“目標”
$(window).bind('resize',function(){
$("#resizeme").css("height","");
if($("#resizeme").outerHeight() < $(window).height()){
$("#resizeme").height($(window).height());
$("body").css("overflow-y","hidden");
}else{
$("body").css("overflow-y","scroll");
}
});
也許我誤解了這個問題,但你為什么要使用Javascript? 這看起來像布局(CSS)問題。 我沒有JS的解決方案: http : //jsfiddle.net/2yKgQ/27/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.